BufferedReader和BufferedWriter的简单使用

BufferedReader和BufferedWriter是为了提高字符读写速度引入的缓冲机制,两个类中分别拥有8192个字符缓冲区,要读写时就优先将要读写的数据存入缓冲区,而不是直接操作文件对象。

package com.sise.group;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class input {
     
     public static void main(String[] args) throws IOException {
     
          File file = new File("../a.txt");
          BufferedWriter w = new BufferedWriter(new FileWriter(file));
          w.write("123asd");
          w.newLine();
          w.write("321asd");
          w.close();
          // 1. 逐个字符读取
          BufferedReader r1 = new BufferedReader(new FileReader(file));
          int str1 = 0;
          while ((str1 = r1.read()) != -1) {
     
              // 因为读取到的是int类型的,所以要强制类型转换
              System.out.print((char) str1);
          }
          r1.close();
          
          System.out.println();
          // 2. 逐行读取
          BufferedReader r2 = new BufferedReader(new FileReader(file));
          String str2;
          while ((str2 = r2.readLine()) != null) {
     
              System.out.print(str2 + "\n");
          }
          r2.close();
     }
}

你可能感兴趣的:(java)