一、需求说明
需求原因:项目由于某种原因不能提交SVN,需将已经写好的源码给另一个同事,不想每次都去创建目录
操作系统:Windows
IDE:Eclipse
需求:Eclipse下直接使用Copy Qualified Name 得到值后,粘贴在配置文件中后运行程序即可实现复制文件(没有文件夹自动创建)
性能:无性能要求,能用就行
二、Jar包依赖
依赖包下载地址:
https://repo1.maven.org/maven2/commons-io/commons-io/2.5/commons-io-2.5.jar
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
三、代码实现
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class SimpleCopyJavaFile {
public static void main(String[] args) throws IOException {
String userName = "你的Windows系统用户名";
String destParentPath = "C:/Users/"+userName+"/Desktop/temp";
String srcParentPath = "D:/workspace";
String configPath = "C:/Users/"+userName+"/Desktop/1.txt";
copyFile(configPath, destParentPath, srcParentPath);
System.out.println("done");
}
/**
* 导出文件夹处理(如不存在则创建)
* @param parentPath 父路径(如D:/workspace)
* @param childrenPath 子路径(文件名,如1.txt)
* @return
*/
private static File createFolder(String parentPath,String childrenPath){
StringBuilder builder = new StringBuilder();
builder.append(parentPath)
.append(childrenPath);
File file = new File(builder.toString());
File parentFile = file.getParentFile();
if(!parentFile.exists()){
parentFile.mkdirs();
}
return file;
}
/**
* 复制文件
* @param configPath 控制导出哪个文件的配置文件
* @param destParentPath 导出父路径
* @param srcParentPath 项目所在的路径(待优化)
* @throws IOException
*/
private static void copyFile(String configPath,String destParentPath,String srcParentPath) throws IOException{
String childrenPath;
FileReader reader = new FileReader(configPath);
BufferedReader bf = new BufferedReader(reader);
while((childrenPath = bf.readLine())!=null){
if(childrenPath != null && childrenPath.length() > 0){
File destFile = createFolder(destParentPath,childrenPath);
String srcPath = srcParentPath + childrenPath;
File srcFile = new File(srcPath);
FileUtils.copyFile(srcFile,destFile);
}
}
bf.close();
}
}