Home Tutorial Java Core Files Read file into String

 
 

Share on Google+Share on Google+
Read file into String
Posted on: April 3, 2006 at 12:00 AM
Advertisement
In this section, you will learn how to read a file into the string.

Read file into String

In this section, you will learn how to read a file into the string. 

Description of code:

You can use any input stream but it is better to use FileReader class for reading  the textual input. In the given example we have used BufferedReader class along with FileReader class to read data from the file using it's read() method. This data is then stored into the StringBuffer. At last, we have extracted the string from the StringBuffer and displayed it on the console. 

Here is the code:

import java.io.*;

class FileToString {
  public static void main(String[] argsthrows Exception {
    StringBuffer buffer = new StringBuffer();
    BufferedReader reader = new BufferedReader(
        new FileReader("C:/file.txt"));
    char[] ch = new char[1024];
    int n = 0;
    while ((n = reader.read(ch)) != -1) {
      buffer.append(ch, 0, n);
    }
    reader.close();
    String str = buffer.toString();
    System.out.println(str);
  }
}

In the above code we have used FileReader and BufferedReader class to read the file into memory.

Advertisement

Related Tags for Read file into String:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 3, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com