gpt4 book ai didi

java - 无法在 Java 中复制 "My Documents"

转载 作者:可可西里 更新时间:2023-11-01 09:20:00 26 4
gpt4 key购买 nike

我正在尝试将文件、文件夹、子文件夹、zip 文件等从给定位置复制到另一个位置。我使用了下面的代码。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyDirectoryExample
{
public static void main(String[] args)
{
File srcFolder = new File("C:\\Users\\Yohan\\Documents");
File destFolder = new File("D:\\Test");

//make sure source exists
if(!srcFolder.exists()){

System.out.println("Directory does not exist.");
//just exit
System.exit(0);

}else{

try{
copyFolder(srcFolder,destFolder);
}catch(IOException e){
e.printStackTrace();
//error, just exit
System.exit(0);
}
}

System.out.println("Done");
}

public static void copyFolder(File src, File dest)
throws IOException{

if(src.isDirectory()){

//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}

//list all the directory contents
String files[] = src.list();

for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}

}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);

byte[] buffer = new byte[1024];

int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}

in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
}

现在,我使用上面的代码复制了“我的文档”。但不幸的是,它在运行一段时间后以 NullPointerException 结束。

错误的原因是它试图复制“我的音乐”文件夹,该文件夹甚至不在“我的文档”文件夹中。我在两台运行 Windows 7 的不同机器上测试了这段代码,两台机器都出现了同样的错误。

Windows 特定的解决方案对我来说很好,因为我目前的目标是 Windows 机器。我做错了什么?

我得到的错误如下

Directory copied from C:\Users\Yohan\Documents\My Music  to D:\Test\My Music
Exception in thread "main" java.lang.NullPointerException
at CopyDirectoryExample.copyFolder(CopyDirectoryExample.java:51)
at CopyDirectoryExample.copyFolder(CopyDirectoryExample.java:56)
at CopyDirectoryExample.main(CopyDirectoryExample.java:25)

最佳答案

这不起作用的原因是因为“我的音乐”、“我的图片”(或图像)和其他目录只是符号链接(symbolic link)。请参阅这篇关于如何检测符号链接(symbolic link)的帖子:Java 1.6 - determine symbolic links

关于java - 无法在 Java 中复制 "My Documents",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30401920/

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