FileReader类的read()方法可以按照字符大小读取
-
FileReader fr = new FileReader("aaa.txt"); //创建输入流对象,关联aaa.txt int ch; while((ch = fr.read()) != -1) { //将读到的字符赋值给ch System.out.println((char)ch); //将读到的字符强转后打印 } fr.close(); //关流
FileWriter类的write()方法可以自动把字符转为字节写出
FileWriter fw = new FileWriter("aaa.txt"); fw.write("aaa"); fw.close();
字符流的拷贝
FileReader fr = new FileReader("a.txt"); FileWriter fw = new FileWriter("b.txt"); int ch; while((ch = fr.read()) != -1) { fw.write(ch); } fr.close(); fw.close();
自定义字符数组的拷贝
-
FileReader fr = new FileReader("aaa.txt"); //创建字符输入流,关联aaa.txt FileWriter fw = new FileWriter("bbb.txt"); //创建字符输出流,关联bbb.txt int len; char[] arr = new char[1024*8]; //创建字符数组 while((len = fr.read(arr)) != -1) { //将数据读到字符数组中 fw.write(arr, 0, len); //从字符数组将数据写到文件上 } fr.close(); //关流释放资源 fw.close();
带缓冲的字符流
- BufferedReader的read()方法读取字符时会一次读取若干字符到缓冲区, 然后逐个返回给程序, 降低读取文件的次数, 提高效率
- BufferedWriter的write()方法写出字符时会先写到缓冲区, 缓冲区写满时才会写到文件, 降低写文件的次数, 提高效率
-
BufferedReader br = new BufferedReader(new FileReader("aaa.txt")); //创建字符输入流对象,关联aaa.txt BufferedWriter bw = new BufferedWriter(new FileWriter("bbb.txt")); //创建字符输出流对象,关联bbb.txt int ch; while((ch = br.read()) != -1) { //read一次,会先将缓冲区读满,从缓冲去中一个一个的返给临时变量ch bw.write(ch); //write一次,是将数据装到字符数组,装满后再一起写出去 } br.close(); //关流 bw.close();
readLine()和newLine()方法
- BufferedReader的readLine()方法可以读取一行字符(不包含换行符号)
- BufferedWriter的newLine()可以输出一个跨平台的换行符号" "
-
BufferedReader br = new BufferedReader(new FileReader("aaa.txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("bbb.txt")); String line; while((line = br.readLine()) != null) { bw.write(line); //bw.write(" "); //只支持windows系统 bw.newLine(); //跨平台的 } br.close(); bw.close();
使用指定的码表读写字符
- FileReader是使用默认码表读取文件, 如果需要使用指定码表读取, 那么可以使用InputStreamReader(字节流,编码表)
- FileWriter是使用默认码表写出文件, 如果需要使用指定码表写出, 那么可以使用OutputStreamWriter(字节流,编码表)
-
BufferedReader br = //高效的用指定的编码表读 new BufferedReader(new InputStreamReader(new FileInputStream("UTF-8.txt"), "UTF-8")); BufferedWriter bw = //高效的用指定的编码表写 new BufferedWriter(new OutputStreamWriter(new FileOutputStream("GBK.txt"), "GBK")); int ch; while((ch = br.read()) != -1) { bw.write(ch); } br.close(); bw.close();