import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopy {
public static void testCopyFolder() {
String sourceFilePath = "D:\\java_test";
String targetFilePath = "D:\\alex-test";
copyFile(sourceFilePath, targetFilePath);
// int sourceFileNum = new File(sourceFilePath).listFiles().length;
// int targetFileNum = new File(targetFilePath + "\\"+ new File(sourceFilePath).getName()).listFiles().length;
}
public static void testCopyFile() {
String sourceFilePath = "D:\\test1.txt";
String targetFilePath = "D:\\alex-test";
copyFile(sourceFilePath, targetFilePath);
System.out.println("Copy complete...");
}
/**
* 如需测试,请先把”第8题测试“文件夹中的文件复制到D盘根目录
*/
public static void main(String[] args) {
File file = new File("D:\\test2.txt");
if (!file.exists()) {
try {
file.createNewFile();
System.out.println("file name is " + file.getName());
file = file.getAbsoluteFile();
System.out.println("absolute file is " + file);
System.out.println("new File is created");
} catch (IOException e) {
e.printStackTrace();
}
}
testCopyFolder();
testCopyFile();
}
/**
* @param sourceFilePath
* 文件复制源
* @param targetFilePath
* 文件复制目标端
*/
public static void copyFile(String sourceFilePath, String targetFilePath) {
File sourceFile = new File(sourceFilePath);
File[] sourceFiles = null;
if (sourceFile.isDirectory()) {
targetFilePath += "\\" + sourceFile.getName();
File targetFile = new File(targetFilePath);
targetFile.mkdirs();
sourceFiles = sourceFile.listFiles();
} else if (sourceFile.isFile()) {
sourceFiles = new File[] { sourceFile };
}
for (int i = 0; i < sourceFiles.length; i++) {
if (sourceFiles[i].isDirectory()) {
String newSourceFilePath = sourceFilePath + "\\"+ sourceFiles[i].getName();
copyFile(newSourceFilePath, targetFilePath);
} else {
try {
FileInputStream fis = new FileInputStream(sourceFiles[i]);
FileOutputStream fos = new FileOutputStream(targetFilePath+ "\\" + sourceFiles[i].getName());
int read = -1;
while ((read = fis.read()) != -1) {
fos.write(read);
}
fos.flush();
fos.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}