java.io.File返回值实验

工作中遇到几个bug都是File文件系统的空指针异常,今天特地写了个实验搞清楚一下。
很简单,先上结论,后面是实验程序。

结论

File file = new File(path);

小结论
1. 若path!=null,则file!=null;若path==null,则抛出NullPointerException;因此可以认为new File()不会返回null
2. file.exists()查询【执行时刻】路径是否存在,而【非new File()时刻】;若路径存在,则file.exists()为真;否则为假(路径非法或不存在)
注意,若路径非法,但只要能通过编译,该非法路径会被当做文件名,路径为java程序所在目录,file对象也不会为null
3. file.exists()为假时,file.isFile() / file.isDirectory() 均为假
4. file.exitst() && file.isDirectory() 为真时,file.listFiles()返回数组;否则返回null
5. file.list()/listFIles()返回null,可能原因:file不存在,或不是目录,或没有没有访问权限(android经常是这个原因)

大结论

  1. file = new File(path) 永远不会为null;file是否为null与文件物理状态没有任何关系
  2. File的方法查询的是文件系统即时状态(方法被调用时,立刻查询一次文件系统现在的状态)

一定不会出错的写法

其实就是玩命判空…

    /**
     * 查询目录下内容
     * 永远不会出错的写法
     * @param path
     */
    public static void alwaysWorksMethod(String path) {
        if (path != null) {//需判空
            File file = new File(path);
            if (file != null) {//不需判空,但无妨
                if (file.exists() && file.isDirectory()) {
                    File[] files = file.listFiles();
                    if (files != null) {//需判空
                        for (int i = 0; i < files.length; i++) {
                            System.out.println(files[i].getName());
                        }
                    }
                }
            }
        }
    }

实验程序

测试new File(path) 创建情况:path为null时;path不为null但指定文件不存在时;
测试file.listFile()返回值:file不存在时;file存在但不是目录时;创建file时存在,但listFile()时不存在的情况;

package com.kwws.demo;

import java.io.File;

public class FileSystem {
    public static void main(String[] args) {
        String pathNull = null;
        String pathIllegal = "e:ill、/egal|path.tx";//非法路径
        String pathNotExistFile = "e:/a/notexistfile.txt";//不存在的文件
        String pathNotExistDir = "e:/a/notexistdir";//不存在的文件夹
        String pathExistFile = "e:/a/existfile.txt";//存在的文件
        String pathExistDir = "e:/a/existdir";//存在的文件夹,有1个子文件夹,2个文件

        //      File fileNull = new File(pathNull);//结论:运行时抛出NullPointerException:如api所言,参数path不能为null
        File fileIllegal = new File(pathIllegal);
        File fileNotExist = new File(pathNotExistFile);
        File dirNotExist = new File(pathNotExistDir);
        File fileExist = new File(pathExistFile);
        File dirExist = new File(pathExistDir);

        //      test(fileNull, "pathNull");
        test(fileIllegal, "pathIllegal");//结论:只要编译通过,非法路径也会被当做文件名,所在路径为java程序所在路径
        test(fileNotExist, "pathNotExistFile");
        test(dirNotExist, "pathNotExistDir");
        test(fileExist, "pathExistFile");
        test(dirExist, "pathExistDir");

        //文件变动
        System.out.println("\n------delete test");
        testDelete();

        //不会出错的写法
        System.out.println("\n------always works method");
        alwaysWorksMethod(pathExistDir);
    }

    static void test(File file, String testName) {
        System.out.println("\n------" + testName);
        if (file == null) {
            System.out.println("File obj is null");
        } else {
            if (file.exists()) {
                System.out.println("File exists = " + file.getAbsolutePath());
                if (file.isFile()) {
                    System.out.println("  this File obj is a file.");
                }
                if (file.isDirectory()) {
                    System.out.println("  this File obj is a dir.");
                }
            } else {//对不存在的文件的调用
                System.out.println("File not exists = " + file.getAbsolutePath());
                if (file.isFile()) {
                    System.out.println("  this File obj is a file.");
                }
                if (file.isDirectory()) {
                    System.out.println("  this File obj is a dir.");
                }
            }

            File[] files = file.listFiles();
            if (files == null) {
                System.out.println("    obj.listFiles() return null.");
            } else {
                System.out.println("    obj.listFiles().length = " + files.length);
            }
        }
    }

    public static void testDelete() {
        String path = "e:/a/testdir";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        System.out.println("obj.exists() == " + file.exists());
        System.out.println("dir.listFiles() is" + (file.listFiles() == null ? "" : " not") + " null");
        file.delete();
        if (file == null) {
            System.out.println("obj is null after delete().");
        } else {
            System.out.println("obj is still not null after delete().");
            System.out.println("obj.exists() == " + file.exists());
            System.out.println("dir.listFiles() is" + (file.listFiles() == null ? "" : " not") + " null");
        }
    }
}

输出:

——pathIllegal
File not exists = e:\JavaProject\JavaDemo\ill、\egal|path.tx
obj.listFiles() return null.
——pathNotExistFile
File not exists = e:\a\notexistfile.txt
obj.listFiles() return null.
——pathNotExistDir
File not exists = e:\a\notexistdir
obj.listFiles() return null.
——pathExistFile
File exists = e:\a\existfile.txt
this File obj is a file.
obj.listFiles() return null.
——pathExistDir
File exists = e:\a\existdir
this File obj is a dir.
obj.listFiles().length = 3
——delete test
obj.exists() == true
dir.listFiles() is not null
obj is still not null after delete().
obj.exists() == false
dir.listFiles() is null
——always works method
1
1.txt
2.txt

水了一篇文章 :)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KwCoding

谢了老板您讷~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值