Java流实例-文件复制

时间:2021-02-12 21:00:11
package ggg;
import java.io.*;
public class test {
public static void main(String[] args) throws IOException {
//源文件
long startTime = System.currentTimeMillis(); // 获取开始时间
File outFile = new File("c:" + File.separator + "Demo" + File.separator + "demo.txt");
File inFile = new File("d:" + File.separator + "Area" + File.separator + "aaa.txt");
if(!outFile.getParentFile().exists()){
System.out.println("源文件路径错误 !");
System.exit(1);
}
if(!outFile.exists()){
System.out.println("源文件不存在!");
System.exit(1);
}
//检查复制路径
if(!inFile.getParentFile().exists()){
inFile.getParentFile().mkdirs();
}
if(!inFile.exists()){
inFile.createNewFile();
}
InputStream in = new FileInputStream(outFile);
OutputStream out = new FileOutputStream(inFile);
byte [] data = new byte[2048];
int temp = 0;
while ( ( temp = in.read( data ) ) != -1 ){
out.write( data, 0, temp);
}
out.close();
in.close();
long endTime = System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间为:" + (endTime-startTime)+"毫秒");
}
}