之前内容:
1. 字节缓冲区
1.1 字节缓冲输出流
BufferedOutputStream
public class Main {
public static void main(String[] args) throws Exception {
String path = "D:\\java\\git\\repository\\lanqiao\\src\\a.txt";
File file = new File(path);
OutputStream os = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(os, 1024);//设置缓冲区的大小为1K
int n = 0;
int cur = 0;
while (n < 10000) {
bos.write(cur);
cur++;
n++;
}
bos.flush();
bos.close();
}
}
结果:
1.2 字节缓冲输入流
BufferedInputStream
public class Main {
public static void main(String[] args) throws Exception {
String path = "D:\\java\\git\\repository\\lanqiao\\src\\a.txt";
File file = new File(path);
InputStream os = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(os, 1024);
int res;
while((res = bis.read()) != -1){
System.out.print((char)res);
}
bis.close();
}
}
结果:
2. 字符
字符缓冲输出流
BufferedIWriter
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
String path = "D:\\java\\git\\repository\\lanqiao\\src\\a.txt";
File file = new File(path);
Writer writer = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(writer,1024);
int n = 0;
int cur = 48;
while(n<10000){
bw.write(cur);
if(cur > 128) {
cur = 48;
bw.write('\n');
}
cur++;
n++;
}
bw.close();
}
}
结果:
字符缓冲输出流
BufferedIReader
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
String path = "D:\\java\\git\\repository\\lanqiao\\src\\a.txt";
File file = new File(path);
Reader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader,1024);
String res="";
while(res != null){
res = br.readLine();
System.out.println(res);
}
br.close();
}
}
结果: