Java连载98-FileReader和FileWriter详解
Posted ruigege0000
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java连载98-FileReader和FileWriter详解相关的知识,希望对你有一定的参考价值。
一、FileReader详解
1.java.io.Reader
java.io.InputStreamReader;转换流(字节输入流--->字符输入流)
java.io.FileReader?;文件字符输入流
2.java.io.Writer
java.io.OutputStreamWriter;转换流(字节输出流-->字节输出流)
java.io.FileWriter;文件字符输出流
package com.bjpowernode.java_learning; import java.io.*; public class D98_1_FileReaderAnalysis { public static void main(String[] args) { FileReader fr = null; FileWriter fw = null; try { //创建文件字符输入流 fr = new FileReader("C:Userslenovo1WorkspacesMyEclipse CIJava_learningsrccomjpowernodejava_learning emp1.txt"); //开始读 char[] chars = new char[512];//1kb int temp = 0; while((temp=fr.read(chars)) != -1) { //将char数组有效部分转换为字符串 System.out.println(new String(chars,0,temp)); //有一好处,读取文本类不会出现乱码,因为每次读取一个字符,而不是字节 } //创建文件字符输出流 fw = new FileWriter("C:Userslenovo1WorkspacesMyEclipse CIJava_learningsrccomjpowernodejava_learning emp2.txt"); //开始写 fw.write("牛逼!"); //将char数组的一部分写入 char[] chars2 = { ‘我‘,‘是‘,‘中‘,‘国‘,‘人‘ }; fw.write(chars2); //刷新 fw.flush(); //关闭 fw.close(); //文件复制,只能复制纯文本文件 FileReader fr2 = new FileReader("C:Userslenovo1WorkspacesMyEclipse CIJava_learningsrccomjpowernodejava_learning emp1.txt"); FileWriter fr3 = new FileWriter("C:Userslenovo1WorkspacesMyEclipse CIJava_learningsrccomjpowernodejava_learning emp2.txt"); char[] chars3 = new char[512]; int temp2 = 0; while((temp2=fr2.read())!= -1) { fr3.write(chars3,0,temp2); } fr3.flush(); fr3.close(); }catch(Exception e) { e.printStackTrace(); }finally { } } }
二、源码:
D98_1_FileReaderAnalysis.java
D97_2_CompleteCopyFile.java
https://github.com/ruigege66/Java/blob/master/D98_1_FileReaderAnalysis.java
https://github.com/ruigege66/Java/blob/master/D97_2_CompleteCopyFile.java
2.CSDN:https://blog.csdn.net/weixin_44630050
3.博客园:https://www.cnblogs.com/ruigege0000/
4.欢迎关注微信公众号:傅里叶变换,个人公众号,仅用于学习交流,后台回复”礼包“,获取大数据学习资料
以上是关于Java连载98-FileReader和FileWriter详解的主要内容,如果未能解决你的问题,请参考以下文章