java中IO字符缓冲流的使用
字符缓冲流的基础使用
/*
* 字符缓冲流
* BufferedWriter和BufferedReader
* */
import java.io.*;
public class Buffer {
public static void main(String[] args) throws IOException {
/*
* 构造方法源码
* public BufferedReader(Reader in) {
this(in, defaultCharBufferSize);
}
*
* public BufferedWriter(Writer out) {
this(out, defaultCharBufferSize);
}
* */
BufferedReader br = new BufferedReader(new FileReader("java基础\\src\\com\\io\\buffer\\chars\\java.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("java基础\\src\\com\\io\\buffer\\chars\\java.txt"));
// 写入数据
bw.write("你好");
// 刷新数据
bw.flush();
// 读取数据
char[] chars = new char[1024];
int length;
while ((length = br.read(chars)) != -1){
System.out.println(new String(chars,0,length));
}
// 关闭资源
bw.close();
br.close();
}
}
使用字符缓冲流进行复制java文件
/*
* 使用字符缓冲流
* 将Before.java复制到Copy.java
* */
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException {
// 数据源
BufferedReader br = new BufferedReader(new FileReader("java基础\\src\\com\\io\\buffer\\chars\\copy\\Before.java"));
// 目标
BufferedWriter bw = new BufferedWriter(new FileWriter("java基础\\src\\com\\io\\buffer\\chars\\copy\\Copy.java"));
// 读取数据源
char[] chars = new char[1024];
int readLength;
while ((readLength = br.read(chars)) != -1){
// 写入数据
bw.write(chars,0,readLength);
}
// 关闭资源
bw.close();
br.close();
}
}