从内存到硬盘 读操作 从硬盘到内存 写操作
package com.file;
import java.io.*;
public class CopyTest {
public static void main(String[] args) {
File srcFile = new File("E:\\JavaSE\\code");
File destFile = new File("F:\\JAVA108\\compare");
copy(srcFile,destFile);
}
public static void copy(File srcFile,File destFile){
if(srcFile.isFile()){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcFile);
String path = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath()+"\\") + srcFile.getAbsolutePath().substring(3);
fos = new FileOutputStream(path);
byte[] bytes = new byte[1024 * 1024];
int readCont = 0;
while ( (readCont = fis.read(bytes)) != -1){
fos.write(bytes,0,readCont);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fis != null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos != null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return;
}
File[] files = srcFile.listFiles();
for (File file : files) {
if(file.isDirectory()){
String srcdir = file.getAbsolutePath();
String destdir = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath()+"\\") + srcdir.substring(3);
File newFile = new File(destdir);
if( !newFile.exists()){
newFile.mkdirs();
}
}
copy(file,destFile);
}
}
}
|