Java InputStreamReader create with encoding

Description

Java InputStreamReader create with encoding

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class Main {
  public static void main(String[] argv) {

    try {//from w  w  w  . j  a  v  a  2  s  .c om
      InputStream is = new FileInputStream("Main.java");
      String s = convertStreamToString(is);
      System.out.println(s);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static String convertStreamToString(InputStream is) throws IOException {
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
      Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
      int n;
      while ((n = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, n);
      }
    } finally {
      is.close();
    }
    return writer.toString();
  }
}



PreviousNext

Related