如何解决线程中的异常" main"复制文件/目录时的java.lang.NullPointerException

时间:2017-04-29 20:05:33

标签: java nullpointerexception file-copying

我有这个代码示例将文件和目录从一个位置复制到另一个位置。但是每次运行程序时都会出现此异常。有人可以帮我找出错误吗?

线程中的异常" main"显示java.lang.NullPointerException

public void listFilesAndFilesSubDirectories(String directoryName) throws FileNotFoundException, IOException {
    File directory = new File(directoryName);
    //get all the files from a directory
    File[] fList = directory.listFiles();
    for (File file : fList) {
        if (file.isFile()) {
            //System.out.println(file.getAbsolutePath());
            System.out.println("File");

            File source = new File("C:\\Users\\Core i3\\Desktop\\Check me\\" + file);
            File dest = new File("C:\\Users\\Core i3\\Desktop\\New folder");
            System.out.println(source);

            InputStream is = null;
            OutputStream os = null;
            try {
                is = new FileInputStream(source);
                os = new FileOutputStream(dest);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
            } finally {
                is.close();
                os.close();
            }

        } else if (file.isDirectory()) {
            listFilesAndFilesSubDirectories(file.getAbsolutePath());

            System.out.println("Directory");

            File source = new File("C:\\Users\\Core i3\\Desktop\\Check me\\" + file);
            File dest = new File("C:\\Users\\Core i3\\Desktop\\New folder");

            InputStream is = null;
            OutputStream os = null;
            try {
                is = new FileInputStream(source);
                os = new FileOutputStream(dest);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
            } finally {
                is.close();
                os.close();
            }

        }
    }

}

0 个答案:

没有答案