java - 怎么避免listFiles()方法读取没有访问权限的文件时返回null?
PHP中文网
PHP中文网 2017-04-18 10:04:38
0
2
826

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中文网

认证0级讲师

reply all(2)
伊谢尔伦

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

小葫芦

Can be achieved by catching exceptions

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!