如何绕过不可访问的文件?

时间:2016-11-11 01:41:44

标签: java file nullpointerexception

我正在尝试在我选择的目录中找到所有已命名的文件。当我执行C:\Program FilesC:\Users之类的操作时,我所使用的代码。但当我c:/时,我会被卡在回收站中并获得java.lang.NullPointerException 并停在c:\$Recycle.Bin\S-1-5-21-1478355014-127360780-1969717230-1002144

public void DirectorySerch(String target, String dirName){
    File f = new File(dirName); System.out.println("H");
    if(!f.isDirectory()){
        throw new IllegalArgumentException("that is not a valid directory");
    }
    for(File folderItem : f.listFiles()){
        if(folderItem.isDirectory()){
            System.out.println(folderItem.getAbsolutePath());
            if(!folderItem.equals("")){
                DirectorySerch(target,folderItem.getPath());
            }
            // Return the result if it is not empty
            /*  if (!result.equals(folderItem.getName())){
            files[filesFounfd] = folderItem.getAbsolutePath();
            filesFounfd++;
            }*/
        }else{
            if(folderItem.getName().equals(target)){
                files[filesFounfd] = folderItem.getAbsolutePath();
                System.out.println(folderItem.getAbsolutePath());
                filesFounfd++;
            }
        }        
    }
}

如果不需要处理回收站,我该怎么办才能解决这个问题呢?

2 个答案:

答案 0 :(得分:1)

 for(File folderItem : f.listFiles()){

问题出在这里。 listFiles()可以返回null,并且所有这些语法都可以用于抛出NPE。改为:

 File[] files = f.listFiles();
 if (files != null) {
    for(File folderItem : files){

答案 1 :(得分:-1)

所以事实证明你可以通过尝试捕捉for循环

来解决这个问题
    public void DirectorySerch(String target, String dirName) {
    File f = new File(dirName);
    System.out.println("H");
    if (!f.isDirectory()) {
        throw new IllegalArgumentException("that is not a valid directory");
    }
    try {
        for (File folderItem : f.listFiles()) {
            if (folderItem.isDirectory()) {
                System.out.println(folderItem.getAbsolutePath());
                if (!folderItem.equals("")) {
                    DirectorySerch(target, folderItem.getPath());
                }
            } else {
                if (folderItem.getName().equals(target)) {
                    files[filesFounfd] = folderItem.getAbsolutePath();
                    System.out.println(folderItem.getAbsolutePath());
                    filesFounfd++;
                }
            }
        }
    }catch(NullPointerException sd){

    }
}