我正在研究一个需要复制包含图像目录的目录的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);
}
}
}
答案 0 :(得分:1)
我认为您的代码有错误!Files.exists(Paths.get(destFolder1),null)属性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()));
}
}
}
}