基于Java语言的IO操作(文件复制)

    public static void main(String[] args) {
//获取复制开始前系统时间毫秒值
long start=System.currentTimeMillis();
//文件复制,先设置源文件位置和目标文件位置
File sourceFile=new File("D:/HAO/movie.mp4");
File descFile=new File("D:/HAO1/movie.mp4");
//读取流
BufferedInputStream reader=null;
//InputStream reader=null;

//写入流
BufferedOutputStream write=null;
//OutputStream write=null;

//循环读取,一边读一边写
try {
reader=new BufferedInputStream(new FileInputStream(sourceFile));
write=new BufferedOutputStream(new FileOutputStream(descFile));
// reader=new FileInputStream(sourceFile);
// write=new FileOutputStream(descFile);
//先定义一个b,读取字节,一个字节一个字节进行读取和写入
// int b;
// while ((b=reader.read())!=-1){ //读
// write.write(b); //写
// }
//或:用字符数组,按数组读取,按数组写入,增加效率
byte[] data=new byte[1024];
int len;
while ((len=reader.read(data))!=-1){ //读
write.write(data,0,len); //写
}
System.out.println("OK");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader!=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (write!=null){
write.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
long end=System.currentTimeMillis();
//获取复制结束后系统时间毫秒值
System.out.println((end-start)+"ms");
}

猜你喜欢

转载自www.cnblogs.com/liusir123/p/11431365.html