首页 / JAVA / 无法用Java复制“我的文档”
无法用Java复制“我的文档”
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了无法用Java复制“我的文档”,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2400字,纯文字阅读大概需要4分钟。
内容图文
![无法用Java复制“我的文档”](/upload/InfoBanner/zyjiaocheng/681/cd5aa0107de645a88532966a7270096f.jpg)
我正在尝试将文件,文件夹,子文件夹,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的2台不同机器上测试了此代码,两者均出现相同的错误.
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)
解决方法:
这不起作用的原因是因为“我的音乐”,“我的图片”(或图像)和其他目录只是符号链接.有关如何检测符号链接的信息,请参见这篇文章:Java 1.6 – determine symbolic links
内容总结
以上是互联网集市为您收集整理的无法用Java复制“我的文档”全部内容,希望文章能够帮你解决无法用Java复制“我的文档”所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。