Java小例子:按指定的编码读取文本文件内容2011-06-11 csdn博客 YidingHeInputStreamReader 的构造函数提供了一个参数,用于指定通过什么编码将 读取到的字节流转换成字符。下面是一个例子:
01./**02. * 读取指定的文本文件,并返回内容03. *04. * @param path文件路径05. * @param charset 文件编码06. *07. * @return 文件内容08. *09. * @throws IOException 如果文件不存在、打开失败或读取失败10. */11.private static String readFile(String path, String charset) throws IOException {12.String content = "";13.BufferedReader reader = null;14.try {15.reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), charset));16.String line;17.while ((line = reader.readLine()) != null) {18.content += line + "
";19.}20.} finally {21.if (reader != null) {22.try {23.reader.close();24.} catch (IOException e) {25.// 关闭 Reader 出现的异常一般不需要处理。26.}27.}28.}29.return content;30.}PS : 这只是一个 InputStreamReader 的用法示例。真的碰到大文件,怎么 可能都读到内存里面来?StringBuffer 都免了。