search

Home  >  Q&A  >  body text

java - 怎么避免listFiles()方法读取没有访问权限的文件时返回null?

listFiles
返回了一个File数组,这时候遍历这个数组会出现NullPointerException

    public static void main(String[] args) {
        File file = new File("D:\\");
        int sum = getTxtSum(file);
        System.out.println(sum);
    }
    
    public static int getTxtSum(File f) {
        File[] subFile = f.listFiles();
        int count = 0;
        for (File file : subFile) {
            if (file.isDirectory()) {
                count += getTxtSum(file);
            }else if(file.isFile() && file.getName().endsWith(".txt")) {
                count += 1;
            }
        }
        
        return count;
    }
PHP中文网PHP中文网2835 days ago878

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:06:38

    Shouldn’t this be judged to see if it is null?

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 10:06:38

    Can be achieved by catching exceptions

    reply
    0
  • Cancelreply