Java File read to String

Description

Java File read to String

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class Main {
  public static void main(String[] argv) {
    readTextFile(new File("Main.java"));
  }/*from  ww  w  .  j a v  a  2 s .  c o m*/

  public static String readTextFile(File filename) {
    try {
      BufferedReader br = new BufferedReader(new FileReader(filename));
      StringBuilder sb = new StringBuilder();
      String line = br.readLine();
      while (line != null) {
        sb.append(line + "\n");
        line = br.readLine();
      }
      br.close();
      return sb.toString();
    } catch (Exception e) {
      e.printStackTrace();
      System.err.println(filename);
      System.err.println(e);
      return "";
    }
  }
}



PreviousNext

Related