提问人:CoderLala 提问时间:4/24/2022 最后编辑:AbraCoderLala 更新时间:4/24/2022 访问量:185
在 Java 中以递归方式复制文件时的 NullPointerException [duplicate]
NullPointerException when recursively copying files in Java [duplicate]
问:
我们有以下练习:给定一个目录和文件列表,然后是目标,复制所有这些目录(递归),然后 文件添加到目标中。
这是我写的代码:
public static void copyFile(File source, File dest) throws IOException {
//use DataOutputStream for its method size() to measure amount of bytes copied
try(FileInputStream is = new FileInputStream(source);
FileOutputStream os = new FileOutputStream(dest);
DataOutputStream dos = new DataOutputStream(os)) {
byte[] buffer = new byte[1000];
int res;
while ((res = is.read(buffer)) !=-1) {
dos.write(buffer, 0, res);
}
int size1 = dos.size();
if(size1<1024){
System.out.println("Total of " + size1 + "B" + " were copied");
}
if(size1>1024){
System.out.println("Total of " + size1/1024 + "KB" + " were copied");
}
if(size1>1e-6){
System.out.println("Total of " + size1/1024/1024 + "MB" + " were copied");
}
}
}
static void recursiveCopy(File file, File Destination){
if(file.isFile()){
try {
System.out.println(">Started: " + file.getAbsolutePath());
copyFile(file, Destination);
System.out.println(">Finished FILE : " + file.getAbsolutePath());
return;
} catch (IOException e) {
e.printStackTrace();
}
}
for(File sub:file.listFiles()){
String indent2 = "";
System.out.println( indent2+ ">Started: " + sub.getAbsolutePath());
recursiveCopy(sub, Destination);
indent2+= " ";
}
}
static void copyAll(File[] listOfFiles, File dest) throws IOException{
for(File f:listOfFiles){
recursiveCopy(f, dest);
System.out.println(" >Finished FOLDER: " + f.getAbsolutePath());
}
}
public static void main(String[] args) throws IOException {
File[] listOfFiles = new File[] {new File("resources/docs/books"),
new File("resources/docs/books/some citations.txt")};
copyAll(listOfFiles, new File("dest"));
}
它抛出以下消息:NullPointerException
线程“main”java.lang.NullPointerException中的异常:无法读取数组长度,因为“<local2>”为空
问题从行开始for(File sub:file.listFiles())
有谁知道我该如何解决这个问题?所有文件和目录都存在,所以我不知道数组的哪个元素可能是空的。也许还有别的什么?
答:
1赞
cyberbrain
4/24/2022
#1
在您的方法中,您要么是一个文件(您将其匹配),要么是一个文件夹。您可以使用 for 循环来处理它。但它不能两者兼而有之,所以当它是一个文件时,你不能获取里面的文件列表(因为没有)。在这种情况下,请跳过 for 循环。recursiveCopy
file
.isFile()
评论
File
file.listFiles()