java 实现复制文件到指定目录
将resource下的目录及文件,复制一份到指定目录,代码实现
import cn.hutool.core.io.FileUtil;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import java.io.File;
import java.io.IOException;
/**
* @author Lenovo
*/
public class StaticResourcesInit {
/**
* 将resource下的目录,复制一份到指定目录
* @param resourcePath resource下的目录,会读取下面的文件(不包含本身)
* @param newRootPath 新的根目录
* @param force 是否强制刷新,true表示会删除新的根目录下的所有文件
*/
public void copyResources(String resourcePath,String newRootPath,boolean force) {
File newRootFile = new File(newRootPath);
if(newRootFile.exists() && force) {
System.out.println("删除新的根目录"+newRootPath+":"+ FileUtil.del(newRootFile));
}
String rootPath = this.getClass().getClassLoader().getResource("static").getPath();
if("\\".equals(File.separator)) {
if(rootPath.startsWith("/")) {
rootPath = rootPath.substring(1);
}
rootPath = rootPath.replaceAll("/","\\\\");
}
System.out.println("项目根目录:"+rootPath);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
Resource[] resources = resolver.getResources("classpath:"+resourcePath+"/**");
if(null!=resources || resources.length>0) {
for (Resource resource : resources) {
File file = resource.getFile();
String newFilePath = file.getPath().replace(rootPath,newRootPath);
File newFile = new File(newFilePath);
if(!newFile.exists()) {
FileUtil.copy(file,newFile,true);
System.out.println("源文件:"+file.getAbsolutePath()+"已复制到:"+newFile.getAbsolutePath());
} else {
System.out.println("文件"+newFile.getAbsolutePath()+"已存在,不需要处理...");
}
// FileUtil.copy(file,FileUtil.newFile(file.getPath().replace(rootPath,newRootPath)),true);
}
System.out.println("resource下"+resourcePath+"目录下(不包含本身)的文件已全部复制到"+newRootPath);
} else {
System.out.println("未读取到"+resourcePath+"目录或目录下没有任何文件");
}
} catch (IOException e) {
System.out.println("读取目录:"+resourcePath+"异常,"+e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
new StaticResourcesInit().copyResources("static","D:\\test",true);
}
版权声明:本文为weixin_49585951原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。