字符缓冲流
1.1 字符缓冲流
- BufferedWriter:可以将数据高效的写出
- BufferedReader:可以将数据高效的读入到内存
- 注意 : 字符缓冲流不具备读写功能 , 只提供缓冲区 , 真正读写还是需要依赖于构造接收的基本的字符流
- 构造方法:
- public BufferedWriter(Writer out) : 构造方法中需要接收一个基本的字符输出流
- public BufferedReader(Reader in) : 构造方法中需要接收一个基本的字符输入流
public class BufferedStreamDemo1 {
public static void main(String[] args) throws IOException {
BufferedReader fr =new BufferedReader(new FileReader("F:\\斗罗大陆.txt"));
BufferedWriter fw =new BufferedWriter(new FileWriter("copy111.txt"));
char[] chs=new char[1024];
int len;
while ((len=fr.read(chs))!=-1){
fw.write(chs,0,len);
}
fr.close();
fw.close();
}
}
1.2 字符缓冲流特有的功能
-
BufferedWriter类
- void newLine():写一个行分隔符,会根据操作系统的不同,写入不同的行分隔符
-
BufferedReader类
- public String readLine() :读取文件一行数据, 不包含换行符号 , 读到文件的末尾返回null
public class BufferedStreamDemo2 {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("bac.txt"));
bw.write("远桥之下泛莲舟");
bw.newLine();
bw.write("岱岩石上松溪流");
bw.newLine();
bw.write("万仞翠山梨亭在");
bw.newLine();
bw.write("莫闻空谷声悠悠");
bw.flush();
BufferedReader br = new BufferedReader(new FileReader("bac.txt"));
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
bw.close();
}
}
public class BufferedStreamDemo3 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("day12_demo\\sort.txt"));
String line = br.readLine();
String[] strs = line.split(" ");
int[] arr = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
arr[i] = Integer.parseInt(strs[i]);
}
Arrays.sort(arr);
BufferedWriter bw = new BufferedWriter(new FileWriter("day12_demo\\sort.txt"));
for (int i = 0; i < arr.length; i++) {
bw.write(arr[i] + " ");
bw.flush();
}
br.close();
bw.close();
}
}