之前看了io流一直没懂flush()这个方法究竟干了个什么,后面才弄明白,所以把它记下来
比如我用缓冲流来复制文件
import java.io.*;
public class Test7 {
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedInputStream bis = null;//声明BufferedInputStream
BufferedOutputStream bos = null;//声明BufferedOutputStream
try {
bis = new BufferedInputStream(new FileInputStream("D:/a.txt"));//实例化BufferedInputStream
bos = new BufferedOutputStream(new FileOutputStream("E:/b.txt"));//实例化BufferedOutputStream
int b = 0;//用来读取数据
while((b = bis.read())!=-1){//判断是否到文件结尾
bos.write(b);//写入文件
}
1
} catch (FileNotFoundException e) {
System.out.println("文件不存在!");
System.exit(0);
} catch (IOException e) {
System.out.println("文件读取错误!");
System.exit(0);
}
System.out.println("文件已复制!");
}
}
我先不在1号位置写flush()或者close()方法,程序正常运行,但是运行的结果并没有把a.txt的内容复制到b.txt里面
然后我们把flush()方法加入到1这个位置
try {
bis = new BufferedInputStream(new FileInputStream("D:/a.txt"));//实例化BufferedInputStream
bos = new BufferedOutputStream(new FileOutputStream("E:/b.txt"));//实例化BufferedOutputStream
int b = 0;//用来读取数据
while((b = bis.read())!=-1){//判断是否到文件结尾
bos.write(b);//写入文件
}
bos.flush();
} catch (FileNotFoundException e) {
System.out.println("文件不存在!");
System.exit(0);
} catch (IOException e) {
System.out.println("文件读取错误!");
System.exit(0);
}
再改为close()
try {
bis = new BufferedInputStream(new FileInputStream("D:/a.txt"));//实例化BufferedInputStream
bos = new BufferedOutputStream(new FileOutputStream("E:/b.txt"));//实例化BufferedOutputStream
int b = 0;//用来读取数据
while((b = bis.read())!=-1){//判断是否到文件结尾
bos.write(b);//写入文件
}
bis.close();
} catch (FileNotFoundException e) {
System.out.println("文件不存在!");
System.exit(0);
} catch (IOException e) {
System.out.println("文件读取错误!");
System.exit(0);
}
就是flush方法只有输出流才具备的,而输入流是没有这个方法的