package com.heima.question8;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.junit.Test;
/**
* @author Alex Zhuang
*
*/
public class FileCopy {
@Test
public static void testCopyFolder(){
String sourceFilePath="D:\\java_test";
String targetFilePath="D:\\alex-test";
copyFile(sourceFilePath , targetFilePath);
System.out.println("Copy complete...");
int sourceFileNum = new File(sourceFilePath).listFiles().length;
int targetFileNum = new File(targetFilePath+ "\\"+new File(sourceFilePath).getName()).listFiles().length;
assertEquals(sourceFileNum,targetFileNum);
}
@Test
public static void testCopyFile(){
String sourceFilePath="D:\\test1.txt";
String targetFilePath="D:\\alex-test";
copyFile(sourceFilePath , targetFilePath);
System.out.println("Copy complete...");
assertEquals(true,new File(targetFilePath+"\\"+new File(sourceFilePath).getName()).isFile());
}
/**
* 如需测试,请先把”第8题测试“文件夹中的文件复制到D盘根目录
*/
public static void main(String[] args){
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();
}
}
}
}
}