复制文件可能有多种方案,当然大多项目有专门的全球文件服务器,复制基本走服务,但是对于普通应用来说,文件可能用nas存储,直接通过调用shell复制是最直接和高效的。
这一章,我们只是练习下二进制IO,当然通过java对象来做文件复制。
目标:
java Copy source target
package com.wht.demo.io;
import java.io.*;
/**
* 通过java对象实现文件copy
* 读取源文件,写入目标文件
*
* @author JDIT
*/
public class Copy {
public static void main(String[] args) throws IOException {
//TODO 校验输入参数是否正确
if (args.length != 2) {
System.out.println("请输入copy文件和目标文件");
System.exit(1);
}
String sourcePath = args[0];
String targetPath = args[1];
//TODO 判断源文件是否存在
File sourceFile = new File(sourcePath);
if (!sourceFile.exists()) {
System.out.println("源文件不存在,请检查!");
System.exit(2);
}
//TODO 判断目标文件是否存在
File targetFile = new File(targetPath);
// if (!targetFile.exists()) {
// System.out.println("目标文件不存在,请检查!");
// System.exit(3);
// }
Long startTime = System.currentTimeMillis();
//TODO 复制文件
try (
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile))
) {
byte[] buffer = new byte[1024];//构造一个长度为1024的字节数组
int r= 0;
while ((r = inputStream.read(buffer)) != -1) {
outputStream.write(buffer);
}
System.out.println( "文件复制完成,共用时"+((System.currentTimeMillis()-startTime))+"毫秒");
}
}
}
复制一个288M的一集电视剧,采用new byte[1024]缓冲,值需要0.6秒,当然不涉及网络传输。
如果逐个字节的读取,需要11秒。