当编码方式和解码方式不一致时,会出现乱码
文件字符输入流,继承抽象父类字符输入流(InputStreamReader)
其read()方法从流中按字符读取数据,无论中文还是英文都能一次性读完
import java.io.FileReader; public class Hello{ public static void main(String[] args) throws Exception { //创建FileReader对象 FileReader file = new FileReader("d:\\in.txt"); int data = 0; //每次读取一个字符,无论中文还是英文都能一次性读完 // while ((data = file.read()) != -1){ // System.out.print((char)data); // } int count = 0; //自定义缓冲区时,创建的数组是字符类型 char[] ch = new char[1024]; while ((count = file.read(ch)) != -1){ System.out.println(new String(ch, 0, count)); } file.close(); } }
文件字符输出流,继承抽象父类字符输出流(InputStreamWriter)
其write()方法从流中按字符一次性读取数据,无论中文还是英文都能一次性读完
import java.io.FileWriter; public class Hello{ public static void main(String[] args) throws Exception { //创建FileReader对象 FileWriter file = new FileWriter("d:\\out.txt"); //每次读取一个字符,无论中文还是英文都能一次性读完 file.write("java是最好的编程语言"); file.close(); } }
练习:复制文件
注意:字符流是不能传输图片、文件等二进制文件的
import java.io.FileReader; import java.io.FileWriter; public class Hello{ public static void main(String[] args) throws Exception { FileReader in = new FileReader("d:\\in.txt"); FileWriter out = new FileWriter("d:\\out.txt"); int data = 0; while ((data = in.read()) != -1){ out.write(data); } in.close(); out.close(); } }
缓冲字符输入流,继承抽象父类输入流(Reader)
以其他字符输入流作为参数,先将数据存储在缓冲区中(8K),提高IO效率,减少访问磁盘的次数
readLine()方法可以读取一行
import java.io.BufferedReader; import java.io.FileReader; public class Hello{ public static void main(String[] args) throws Exception { FileReader re = new FileReader("d:\\in.txt"); BufferedReader br = new BufferedReader(re); // int count = 0; // char[] ch = new char[1024]; // while ((count = br.read(ch)) != -1){ // System.out.println(new String(ch, 0, count)); // } //readLine()方法可以按行打印,此时返回值不是int而是String String data = null; while ((data = br.readLine()) != null){ System.out.println(data); } br.close(); } }
缓冲字符输出流,继承抽象父类输出流(Writer)
newLine()方法可以自动换行
import java.io.BufferedWriter; import java.io.FileWriter; public class Hello{ public static void main(String[] args) throws Exception { FileWriter re = new FileWriter("d:\\out.txt"); BufferedWriter br = new BufferedWriter(re); for (int i = 0; i < 10; i++) { br.write("Hello"); //newLine()方法自动换行 br.newLine(); } br.close(); } }