Writer
字符流的使用很简单,和字节输入流类似,以FileWriter
举例:
执行上述代码即可看到在D
盘下创建了一个名为hello.txt
的文件,文件的内容为hello
。
上面代码fw.flush()
和fw.close()
也可以省略fw.flush()
,只写fw.close()
就可以了,但是都省略是不对的,如果都省略你会发现文本没有写入到hello.txt
文件。
Reader
Reader
的使用也很简单,以FileReader
为例:
输出:
hello
+ 1019
个空格
使用上述代码的会输出hello.txt
中的内容,但是会有一个问题:输出hello
的同时还输出了1019
个空格,这是什么原因呢,如何解决这些问题呢?请你思考。
我们在下一关中揭晓答案。
编程要求
请仔细阅读右侧代码,根据方法内的提示,在Begin - End
区域内进行代码补充,具体任务如下:
-
将
src/step3/input/
目录下的input.txt
文件复制到src/step3/output/
目录下; -
复制的新文件命名为
output.txt
; -
input.txt
文件中只有8
个字符。 -
就算是定义8的字节数组,我还是想定义为1K的字节数组,这个感觉很好,nice!!
-
package step3; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Task { public void task() throws IOException{ /********* Begin *********/ String file1 = "src/step3/input/input.txt"; //创建文件 FileReader fr = new FileReader(file1); char[] cbuf = new char[1024];//定义一个1K的字符数组 fr.read(cbuf);//将文件的数据读到数组中 /*FileReader fr = new FileReader(file1); //实例化 char[] ch = new char[8]; //创建数组 fr.read(ch); //将文件的数据读入到数组中(从前到后)这点特别需要注意一下下*/ String file2 = "src/step3/output/output.txt";//创建新的文件 FileWriter fw = new FileWriter(file2);//将其实例化 fw.write(cbuf); // 读入数组中的数据到文件中(从后到前) fr.close(); //输入关闭流 fw.flush(); //输出刷新流 fw.close(); //输出关闭流 /********* End *********/ } }