IO流(字符流FileReader)
字符流:
* 字符流是可以直接读写字符的IO流。
* 字符流读取字符,就要先读取到字节数据,然后转为字符,如果要写出字符,需要把字符转为字节再写出。
什么情况下使用字符流:
* 字符流也可以拷贝文件,但不推荐使用,因为读取时会把字节转为字符,写出时还要把字符转回字节。
* 程序需要读一段文本,或者需要写出一段文本的时候可以使用字符流
* 读取的时候是按照字符的大小读取的,不会出现半个中文。
* 写出的时候可以直接将字符串写出,不用转为字节数组。
注意事项:
* 不可以拷贝非纯文本的文件。(文件会乱码)
IO流(字符流FileWriter)
* FileWriter类的write()方法可以自动把字符转为字节写出。
public static void main(String[] args) throws IOException { // TODO 自动生成的方法存根 FileWriter fw=new FileWriter("eee.txt"); //创建文件 fw.write("六一快乐"); //write():把字符转为字节. fw.close(); //释放资源 }
IO流(字符流拷贝)
public static void main(String[] args) throws IOException { FileReader fr = new FileReader("test.txt"); FileWriter fw = new FileWriter("eeecc.txt"); int b; while ((b = fr.read()) != -1) { fw.write(b); } fr.close(); fw.close(); //必须关闭,如果不关流,就会将内容写到缓冲区,关流会将缓冲区内容刷新,再关闭。 }
IO流(自定义字符数组拷贝)
public static void main(String[] args) throws IOException { FileReader list = new FileReader("test.txt"); FileWriter list2 = new FileWriter("copy.txt"); char[] arr = new char[1024]; int len; while ((len = list.read(arr)) != -1) { list2.write(arr, 0, len); } list.close(); list2.close(); }