您的位置:首页 > 其它

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

2016-02-15 15:52 645 查看
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的话,就抛空指针异常。

@Test
public void testFilePathName() {
File file = null;
file = new File("");
System.out.println(file.getAbsolutePath());
// 打印D:\workspace\test

file = 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.txt

file = new File("test/src/main/resources/dd.txt");
System.out.println(file.getAbsolutePath());
// 打印D:\workspace\test\test\src\main\resources\dd.txt

file = new File("/src/main/resources/dd.txt");
System.out.println(file.getAbsolutePath());
// 打印D:\src\main\resources\dd.txt

file = 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/,注意不是以单斜杠开始的,否则会跑到根路径去的!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: