在项目中根据配置文件路径生成File对象的方法

来源:互联网 发布:appstore无法下载软件 编辑:程序博客网 时间:2024/06/14 06:24

File类最常用的构造方法有两个,File(String pathname) 及File(URI uri) ,其中最最常用的构造方法是File(String pathname),其中这个字符串参数值得探讨一下:

源码中注释是这样写的:

/**     * Creates a new <code>File</code> instance by converting the given     * pathname string into an abstract pathname.  If the given string is     * the empty string, then the result is the empty abstract pathname.     *     * @param   pathname  A pathname string     * @throws  NullPointerException     *          If the <code>pathname</code> argument is <code>null</code>     */    public File(String pathname) {        if (pathname == null) {            throw new NullPointerException();        }        this.path = fs.normalize(pathname);        this.prefixLength = fs.prefixLength(this.path);    }

意思就是说,字符串参数如果是空字符串的话,就返回一个空的抽象路径;如果是null的话,就抛空指针异常。

@Testpublic void testFilePathName() {File file = null;file = new File("");System.out.println(file.getAbsolutePath());// 打印D:\workspace\testfile = new File("/");System.out.println(file.getAbsolutePath());// 打印D:\String pathName = "/test/src/main/resources/dd.txt";file = new File(pathName);System.out.println(file.getAbsolutePath());// 打印D:\test\src\main\resources\dd.txtfile = new File("test/src/main/resources/dd.txt");System.out.println(file.getAbsolutePath());// 打印D:\workspace\test\test\src\main\resources\dd.txtfile = new File("/src/main/resources/dd.txt");System.out.println(file.getAbsolutePath());// 打印D:\src\main\resources\dd.txtfile = new File("src/main/resources/dd.txt");System.out.println(file.getAbsolutePath());// 打印D:\workspace\test\src\main\resources\dd.txt}
如果字符串参数的路径名是相对路径,即不带盘符的情况下,默认情况下,系统是根据用户的工作路径来解释相对路径的。何为工作路径?System.getProperty("user.dir")的值。简单来讲就是这个项目所在的路径,本项目就放在D盘workspace文件夹下,项目名是test,所以工作路径就是D:\workspace\test2。

如果字符串参数是空字符串的话,构造方法返回的还是工作路径;如果是一个单斜杠"/"的话,返回的是项目所在盘的根路径,如D:\;如果传配置文件的限定名的话(右键,Copy Qualified Name得到的值,注意是以斜杠开始的),会发现返回的路径名字符串包含了重复的项目名;去掉/projectName之后传入(此时是以单斜杠开始的字符串),发现返回的路径竟然是根路径加所传的字符串参数;接着把字符串参数开始的单斜杠去掉,传入后返回正确的路径名。所以,传入的字符串参数应该是Qualified Name去掉/projectName/,注意不是以单斜杠开始的,否则会跑到根路径去的!

0 0