转:
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Handoking/article/details/83095380
输入输出的几种形式
1.FileReader,FileWriter
File r = new File("temp.txt") FileReader f = new FileReader(name);//读取文件name BufferedReader b = new BufferedReader(f);//缓冲写入,提供了readline函数,可以按行读取。 Srting str = null; while((str = b.readline()) != null){ System.out.print(str);//按行读取 } //但FileReader涉及编码转换问题,默认系统编码,容易出现乱码
FileWriter writer = new FileWriter("c://test.txt");//FileWriter不会覆盖原来的文本,并且能识别换行符。 BufferedWriter bw = new BufferedWriter(writer);//缓冲写入,提高写入速度 bw.write("已存在的字符串");
2.inputStreamReader,outputStreamWriter
File f = new File("//..//"); InputStreamReader reader = new InputStreamReader(new FileInputStream(f)); BuffeReader br = new BufferedWriter(reader); //FileReader是把文件转换为字符流读入 //FileInputStream是读取字节流 //InputStreamReader将字节转换为字符,同时InputStreamReader的参数中可以自定义编码,这是个重要的特性。 //OutputStreamWriter的用法同InputStreamReader,同样可以用户在其参数中自定义编码方式,比较适合对中文文档的写。
3.按行读写并指定编码方式
//按行读中文文档,为了之后能按行写,先将读到的中文字符串,放入数组 List<String>temp = new ArrayList<>(); File f = new File("c://data.txt"); InputStreamReader reader = new InputStreamReader(new FileInputStream(f),"GBK"); BufferedReader br = new BufferedReader(reader); String str=null; while((str=br.readline())!=null){ temp.append(str); } br.close(); reader.close(); //下面按行读。我实现的其实就是变相的分行打印,如果有更好的方法请大家指教 OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream("out.txt"),"GBK"); BufferedWriter bw = new BufferedWriter(os); PrintWriter out = new PrintWriter(bw); for(String aTemp:temp){ out.println(aTemp); } bw.close(); os.close(); out.close();