Java tutorial
//package com.java2s; //License from project: Apache License import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; public class Main { /** * Read text file from its InputStream. * @param charset Charset of target file. * @param lines_limit The max lines to read. */ public static String readFile(InputStream inputStream, String charset, int lines_limit) { StringBuilder stringBuilder = new StringBuilder(); try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); int i = 0; String str_buffer; while (++i <= lines_limit && (str_buffer = bufferedReader.readLine()) != null) { stringBuilder.append(str_buffer).append("\n"); } if (i >= lines_limit && lines_limit != 1) { //Indicate that the content is part of the file. stringBuilder.append(String.format("... >%d!", lines_limit)); } else if (stringBuilder.length() > 0) { //Remove the final superfluous "\n". stringBuilder.setLength(stringBuilder.length() - 1); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } return stringBuilder.toString(); } public static String readFile(InputStream inputStream, int lines_limit) { return readFile(inputStream, "UTF-8", lines_limit); } public static String readFile(InputStream inputStream, String charset) { return readFile(inputStream, charset, Integer.MAX_VALUE); } /** * Read text file from its InputStream. */ public static String readFile(InputStream inputStream) { return readFile(inputStream, Integer.MAX_VALUE); } /** * Read certain text file. */ public static String readFile(File file) { String result = ""; try { result = readFile(new FileInputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } return result; } /** * Read certain text file. * @param file_str The path of reading text file. */ public static String readFile(String file_str) { return readFile(new File(file_str)); } }