package com.hz.weep; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * 读取文件内容演示类. * @author weep * */ public class FileReaderDemo { /** * @param args */ public static void main(String[] args) { //读取行,临时存值. String line = null; //记录行号. int lineNumber = 0; //装入文件全部内容的builder. StringBuilder result = new StringBuilder(); //不解释了- -. BufferedReader br = null; try { br = new BufferedReader(new FileReader("d:\\a.txt")); //循环取出行. while ((line = br.readLine()) != null) { //拼装行到最后结果 new String(line.getBytes(),"utf-8")这句是要点,把你读取过来的内容按照UTF-8重新编码. result.append(++lineNumber).append(new String(line.getBytes(),"utf-8")).append("\n"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //关闭BufferedReader *重要 if (br != null) { try { br.close(); } catch (IOException e) { } } } //打印最后结果到控制台. System.out.println(result.toString()); } }
最近下载更多