package IOUtilLearn.HelloWorld;
import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//创建源文件和目标文件,将源文件的内容copy到目标文件
//如果源文件不存在或者不是文件,输出异常
public classCopyFile {
public static void CopyFile(File srcFile,File destFile) throwsIOException{
//如果源文件不存在,报异常
if(!srcFile.exists()){
throw newIllegalArgumentException("文件"+srcFile+"不存在!");
}
//如果srcFile不是文件,而是文件夹
if(!srcFile.isFile()){
throw newIllegalArgumentException(srcFile+"不是文件!");
}
//初始化
FileInputStreamin =new FileInputStream(srcFile);
FileOutputStreamout=new FileOutputStream(destFile);
while(in.read()!=-1){
byte[] b = new byte[8*1024];
in.read(b);
out.write(b);
}
in.close();
out.close();
}
}
有三种方式实现数据的读写
1.FileInputStream和FileOutputStream(速度最快)
像上面那种方法,通过数组byte[] b的方式开辟一个大小为8K的内存,实现数组的批量存储,可以有效的优化数据的读写,提高速率
2.DataInputStream和DataOutputStream(速度较慢)
提供writeInt、writeLong等方法便捷的实现数据的读写
3.BufferedInputStream和BufferedOutputStream(速度较快)
通过缓冲区实现数据的读写