自己写的工具类,有不对的地方或者可以优化的地方,希望留言,共同讨论
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFileDirUtil {
public static int IS_EXISTS = 0;
public static void main(String[] args) {
//String sourcePath = "D:/study_project/java-io-test.txt";
//String targetPath = "D:/study_project/java-io-test-to.txt";
String sourcePath = "D:/study_project/test";
String targetPath = "D:/study_project/copyTest";
//copyFile(sourcePath,targetPath);
copyDirectory(sourcePath, targetPath);
}
/**
* 文件的拷贝
* @param sourcePath
* @param targetPath
*/
public static void copyFile(String sourcePath,String targetPath){
File sourceFile = new File(sourcePath);
File targetFile = new File(targetPath);
copyFile(sourceFile, targetFile);
}
/**
* 文件的拷贝
* @param sourceFile
* @param targetFile
*/
public static void copyFile(File sourceFile,File targetFile){
if(!sourceFile.exists()){
System.out.println("源文件没有找到");
return;
}
if(targetFile.exists()){
System.out.println("目标文件已经存在,删除已存在的目标文件");
targetFile.delete();
}
BufferedInputStream fis = null;
BufferedOutputStream fos = null;
int len = 100;
int count = -1;
byte[] buffer = new byte[len];
try {
fis = new BufferedInputStream(new FileInputStream(sourceFile));
fos = new BufferedOutputStream(new FileOutputStream(targetFile));
while ((count=fis.read(buffer, 0, len))!= -1) {
fos.write(buffer, 0, count);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件没有找到");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取异常");
} finally {
try {
fis.close();
fos.close();
} catch (Exception e) {
System.out.println("流关闭异常");
}
}
}
/**
* 文件夹拷贝
* @param sourcePath
* @param targetPath
*/
public static void copyDirectory(String sourcePath,String targetPath){
File sourceFile = new File(sourcePath);
File targetFile = new File(targetPath);
copyDirectory(sourceFile, targetFile);
}
/**
* 文件夹拷贝
* @param sourcePath
* @param targetPath
*/
public static void copyDirectory(File sourceFile,File targetFile){
if(!sourceFile.exists()){
System.out.println("源文件没有找到");
return;
}
if(targetFile.exists() && IS_EXISTS == 0){
System.out.println("目标文件已经存在,删除已存在的目标文件");
targetFile.delete();
IS_EXISTS = 1;
}
if(sourceFile.isDirectory()){
targetFile.mkdir();
}
if(sourceFile.isDirectory()){
File[] listFile = sourceFile.listFiles();
for(File file : listFile){
String newPath = file.getPath();
String newCopyPath = targetFile.getPath()+File.separator+file.getName();
if(file.isDirectory()){
copyDirectory(newPath, newCopyPath);
}else{
copyFile(newPath, newCopyPath);
}
}
}else{
copyFile(sourceFile, targetFile);
}
}
}