在项目中根据配置文件路径生成File对象的方法
2016-02-15 15:52
645 查看
File类最常用的构造方法有两个,File(String pathname) 及File(URI uri) ,其中最最常用的构造方法是File(String pathname),其中这个字符串参数值得探讨一下:
源码中注释是这样写的:
意思就是说,字符串参数如果是空字符串的话,就返回一个空的抽象路径;如果是null的话,就抛空指针异常。
如果字符串参数是空字符串的话,构造方法返回的还是工作路径;如果是一个单斜杠"/"的话,返回的是项目所在盘的根路径,如D:\;如果传配置文件的限定名的话(右键,Copy Qualified Name得到的值,注意是以斜杠开始的),会发现返回的路径名字符串包含了重复的项目名;去掉/projectName之后传入(此时是以单斜杠开始的字符串),发现返回的路径竟然是根路径加所传的字符串参数;接着把字符串参数开始的单斜杠去掉,传入后返回正确的路径名。所以,传入的字符串参数应该是Qualified Name去掉/projectName/,注意不是以单斜杠开始的,否则会跑到根路径去的!
源码中注释是这样写的:
/** * 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/,注意不是以单斜杠开始的,否则会跑到根路径去的!
相关文章推荐
- VsFtpd配置文件详解
- http之206状态码
- 总结云计算/OpenStack/Docker的概念理解
- 理解javascript中的with关键字
- 第43讲:Scala中类型变量Bounds代码实战及其在Spark中的应用源码解析
- 真正的inotify+rsync实时同步 彻底告别同步慢
- 观电影“时间管理局”有感
- 设计模式之六大原则(二)
- cf#342-D - Finals in arithmetic-构造
- vs2010所有的服务器控件都变成了未知元素
- oracle中merge方法
- 仅需6步,教你轻易撕掉app开发框架的神秘面纱(1):确定框架方案
- UITextView,Label加载html代码
- Oracle sys 与system的区别
- Android 官方推荐 : DialogFragment 创建对话框
- nginx使用小结
- Web服务器父与子 Apache和Tomcat区别
- python 汉诺塔
- 1026. 程序运行时间(15)
- 删除目录软链接注意事项