java 我的文档_无法用Java复制“我的文档”

我正在尝试将文件,文件夹,子文件夹,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

标签:io,nullpointerexception,windows,java

来源: https://codeday.me/bug/20191028/1951374.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值