Java tutorial
//package com.java2s; import java.io.BufferedReader; import java.io.File; 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.UnsupportedEncodingException; import java.io.Writer; public class Main { public static final String HTML_ENCODING = "UTF-8"; @Deprecated public static String getStringFromFile(String filePath) { File fl = new File(filePath); FileInputStream fin = null; String ret = null; try { fin = new FileInputStream(fl); ret = convertStreamToString(fin); //Make sure you close all streams. fin.close(); } catch (IOException e) { e.printStackTrace(); } return ret; } public static String getStringFromFile(String pathUrlName, boolean encode) { Writer writer = null; try { InputStream is = new FileInputStream(new File(pathUrlName)); writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader; if (encode) { reader = new BufferedReader(new InputStreamReader(is, HTML_ENCODING)); } else { reader = new BufferedReader(new InputStreamReader(is)); } int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); } return writer.toString(); } public static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } reader.close(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } }