Read file into String


 

Read file into String

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

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.

Ads