在项目中根据配置文件路径生成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
- 在项目中根据配置文件路径生成File对象的方法
- 如何从在JAVA项目中获得配置文件的路径
- 项目中配置文件路径
- File对象的路径
- Java项目中根据相对路径和绝对路径获取文件的方法 getResource(name)
- hibernate在配置文件中配置对象关系映射文件即hbm文件路径的写法
- 在Action中获取项目的服务器路径and读取配置文件common.properties
- 在项目中,如何根据当前的流水号,生成下一个流水号!
- C++从配置文件读取路径,然后在程序中使用的方法
- java中获取当前项目类路径下的配置文件
- 在配置文件(manifest file)中声明activity的一点理解
- Struts2中配置文件在非默认路径下的加载
- JAVA中根据集合中对象属性排序的方法
- 在不同浏览器中获取File Input的路径
- Delphi中根据分类数据生成树形结构的方法
- 根据table逆向生成的DAO类中方法总结
- Unity中根据字符串生成二维码的方法
- 在 Intellij IDEA中设置Maven 路径及配置文件的方法(使用阿里云Maven源)
- Android 官方推荐 : DialogFragment 创建对话框
- Android L中Setupwizard保持竖屏处理
- 多个国内安卓模拟器的认识
- Swift 闭包Closures
- 如何理解handler.postDelayed方法的用途与意义?
- 在项目中根据配置文件路径生成File对象的方法
- 观电影“时间管理局”有感
- sheet
- NDK错误总结
- Android 第十一天
- Zend Studio 中安装emmet插件的方法
- hdu1176 dp
- 浏览器页面渲染基本过程
- iOS学习路线