无法用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

上一篇:Java数组,NullPointerException?


下一篇:android – 单击新用户按钮时应用程序强制关闭