current position:Home>What if the Java access system protection file reports an error NullPointerException

What if the Java access system protection file reports an error NullPointerException

2022-02-03 01:53:32 CSDN Q & A

Write a program to automatically back up files , I copied a method on the Internet and made minor changes :

public static boolean copyFileUsingFileChannels(File source, File dest) throws IOException {    boolean scu;    FileChannel inputChannel = null;    FileChannel outputChannel = null;    try {        inputChannel = new FileInputStream(source).getChannel();        outputChannel = new FileOutputStream(dest).getChannel();        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());        scu = true;    } catch (Exception e) {        scu = false;    }finally {        inputChannel.close();  // In the error report 54 That's ok         outputChannel.close();    }    return scu;}

Replication method :

static int fail = 0;static int error = 0;public static void fileCopy(File file1, File file2) throws IOException {    File[] files1 = file1.listFiles();    if(files1 == null) {    // If it is a system protected folder ,files1 by null        error ++;            // Count : error         return;    }    for (int i = 0; i < files1.length; i++) {                if (files1[i].isDirectory()) {            String s = files1[i].getName();            File file = new File(file2.getPath() + "/" + s);            file.mkdir();            fileCopy(files1[i], file);        // recursive         } else if (files1[i].isFile()) {            System.out.println(files1[i].getPath());  // Output the current file path             String str = files1[i].getPath().substring(                    file1.getPath().length(),                     files1[i].getPath().length());            //GFile Paste path for             File GFile = new File(file2.getPath() + "\\" + str);            /** *  Omit the part : Detect whether it is the same file , The same thing continue; */            if(!Test.copyFileUsingFileChannels(files1[i], GFile))  // In the error report 74 That's ok                 fail++;        // Count : copy failed         }    }}

Now for system protected folders, you can directly skip , But a single file, such as pagefile.sys I don't know how to skip , It still reports an error

h:\pagefile.sysException in thread "main" java.lang.NullPointerException    at bag.Test.copyFileUsingFileChannels(Test.java:54)    at bag.CopyFiles.fileCopy(CopyFiles.java:74)    at bag.CopyFiles.main(CopyFiles.java:89)



Refer to the answer 1:

It's the line you reported wrong inputChannel yes null Null pointer exception caused by , Change that line to :

if(inputChannel != null){ inputChannel.close();}



Refer to the answer 2:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/02/202202030153296072.html

Random recommended