gpt4 book ai didi

java - 使用java复制目录及其内容

转载 作者:行者123 更新时间:2023-12-01 09:06:38 25 4
gpt4 key购买 nike

我正在开发一个java项目,需要复制一个包含图像目录的目录。由于我是Java新手,我自己设计了以下代码来复制目录。但我收到“空指针异常”错误。有人可以帮我改正我的脚本吗?或者给我一些建议?

public CopyDir() throws IOException {
String destFolder1 = System.getProperty("user.home")+"/desktop/pics";
File srcFolder = new File("C:\\rkm_vidyapith\\pics");
if (!Files.exists(Paths.get(destFolder1),null))
new File(destFolder1).mkdirs();
if (srcFolder.isDirectory()) {
for (String DirList : srcFolder.list()) {
File FileList = new File(DirList);
for (String EachFile:FileList.list())
Files.copy(Paths.get(EachFile),
Paths.get(destFolder1),
StandardCopyOption.REPLACE_EXISTING);
}
}
}

最佳答案

我认为您的代码有错误!Files.exists(Paths.get(destFolder1),null) property null 此时不行。我认为有更好的方法来做到这一点。

    import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileCopy {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException{
File sourceDir = new File("c:/tmp/pics");
if (sourceDir.exists()) { // if we have to copy something

File destDir = new File(System.getProperty("user.home") + "/desktop/pics");
destDir.mkdirs(); // ensure that we do have output directory

// do copy with nio lib
Path destPath = destDir.toPath();
doCopy(sourceDir, destPath);
} else {
System.out.println("Source directory doesn't exists!");
}

}

/**
* Do copy.
*
* @param sourceDir the source dir
* @param destPath the dest path
* @throws IOException Signals that an I/O exception has occurred.
*/
private static void doCopy(File sourceDir, Path destPath) throws IOException{
for (File sourceFile : sourceDir.listFiles()) {
if (sourceFile.isDirectory()){
File dPath = destPath.resolve(sourceFile.getName()).toFile();
if (!dPath.exists()){
dPath.mkdir();
}
doCopy(sourceFile, dPath.toPath());
}
else{
Path sourcePath = sourceFile.toPath();
Files.copy(sourcePath, destPath.resolve(sourcePath.getFileName()));
}
}
}
}

关于java - 使用java复制目录及其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41218749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com