read File in UTF-8 - Java java.io

Java examples for java.io:File UTF

Description

read File in UTF-8

Demo Code

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class Main {
  public static void main(String[] argv) throws IOException {
    File f = new File("Main.java");
    System.out.println(readFile(f));
  }//from  w  ww.j  a  va 2  s  .c  o m

  public static String readFile(File f) throws IOException {
    return readStream(new InputStreamReader(new FileInputStream(f), "UTF-8"));
  }

  /**
   *
   * @param reader
   * @return
   * @throws IOException
   */
  public static String readStream(Reader reader) throws IOException {
    StringBuilder result = new StringBuilder();
    BufferedReader in = new BufferedReader(reader);
    String line;
    while ((line = in.readLine()) != null) {
      result.append(line);
      result.append('\n');
    }
    in.close();
    return result.toString();
  }
}

Related Tutorials