【面试题】Java通过IO实现文件拷贝
import java.io.*;
/**
*
* 文件拷贝案例
*/
public class IoDemo {
public static void main(String[] args) {
File oleFile = new File("D:"+File.separator+"test"+File.separator+"123.png");
File sourceFile = new File("D:"+File.separator+"test"+File.separator+"test.png");
try {
System.out.println(copyFile(oleFile , sourceFile));
} catch (IOException e) {
e.printStackTrace();
System.out.println("出错了");
}
}
public static long copyFile(File oleFile , File sourceFile) throws IOException {
if( !oleFile.exists() ){ //文件不存在
throw new FileNotFoundException("文件没有找到");
}
if( !sourceFile.getParentFile().exists()){ // 目标文件夹不存在
sourceFile.getParentFile().mkdirs();
}
long start = System.currentTimeMillis();
InputStream inputStream = new FileInputStream(oleFile); ;
OutputStream outputStream = new FileOutputStream(sourceFile) ; ;
try {
int len = 0 ;
byte [] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1){
outputStream.write(bytes);
}
} finally {
inputStream.close();
outputStream.close();
outputStream.flush();
}
long end = System.currentTimeMillis();
return (end-start);
}
}
输出:
copy耗时: 1
0条评论