编码和解码方式不同,会出现乱码
字节流在读取中文时会将中文拆成单独字节读取,会读成乱码
单字读取:
//1创建FileReader 文件字符输入流 FileReader fileReader = new FileReader("F:\\a.txt"); //2读取 int data = 0; while((data = fileReader.read()) != -1){ System.out.print((char)data); } fileReader.close();
字符串读取:
char[] buf = new char[1024]; int count = 0; while((count = fileReader.read(buf))!= -1){ System.out.println(new String(buf,0,count)); }
//1 创建FileWriter对象 FileWriter fileWriter = new FileWriter("F:\\write.txt"); //2 写入 for (int i = 0; i < 10; i++) { fileWriter.write("java是最好的语言\r\n"); fileWriter.flush(); } fileWriter.close();
字符流读的是字符,图片和其他二进制文件无法读取,会变成乱码。
FileReader fileReader = new FileReader("F:\\write.txt"); FileWriter fileWriter = new FileWriter("F:\\write2.txt"); //write int data = 0; while((data = fileReader.read())!=-1){ fileWriter.write(data); fileWriter.flush(); } fileReader.close(); fileWriter.close();
read()
readLine():读取一行
普通读取
FileReader fileReader = new FileReader("F:\\write.txt"); BufferedReader bufferedReader = new BufferedReader(fileReader); //read char[] buf = new char[1024]; int count = 0; while((count = bufferedReader.read(buf))!= -1){ System.out.println(new String(buf,0,count)); } bufferedReader.close();
FileReader fileReader = new FileReader("F:\\write.txt"); BufferedReader bufferedReader = new BufferedReader(fileReader); //read String line = null; while ((line = bufferedReader.readLine())!=null){ System.out.println(line); } bufferedReader.close();
FileWriter fileWriter = new FileWriter("F:\\buffer.txt"); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); //write for (int i = 0; i < 9; i++) { bufferedWriter.write("cheer on"); bufferedWriter.newLine();//写入一个换行符 bufferedWriter.flush(); } bufferedWriter.close();
//创建打印流 PrintWriter printWriter = new PrintWriter("F:\\print.txt"); //打印 printWriter.println(97);//打印结果就是数字97 printWriter.println(true); printWriter.println('c'); printWriter.println(3.62); printWriter.println("abcdd"); //关闭 printWriter.close(); System.out.println("打印完毕");
可在创建 InputStreamReader
对象时设置编码格式
//1.创建对象,指定读取文件的编码方式 FileInputStream fileInputStream = new FileInputStream("F:\\write.txt"); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"utf-8"); //2.读文件 int data = 0; while ((data = inputStreamReader.read())!=-1){ System.out.print((char)data); } //3.close inputStreamReader.close();
可在创建 OutputStreamReader
对象时设置编码格式
FileOutputStream fileOutputStream = new FileOutputStream("F:\\output.txt"); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"gbk"); for (int i = 0; i < 9; i++) { outputStreamWriter.write("天气真好\r\n"); outputStreamWriter.flush(); } outputStreamWriter.close();