首页 > 编程语言 > 详细

Java从不同目录获取文件方式

时间:2015-02-26 11:32:12      阅读:232      评论:0      收藏:0      [点我收藏+]
demo 
├─src 
│    └─com 
│            └─rgsc
│                    └─xml
│                          ├─XmlRead.java
│                          └─stu.xml
 
 
1. 错误方式:
String filePath="src/com/rgsc/xml/stu.xml";
File f = newFile(filePath);
发布为jar包后读取就会失败,因此不要使用这种方式
 
2. 类字节码方式
String filePath = XmlRead.class.getResource("/com/rgsc/xml/stu.xml").getFile();
// String filePath = XmlRead.class.getResource("stu.xml").getFile();  //可以采用相对路径
File f = new File(filePath);
注:1. 默认从当前类所在包查找,若要从根目录查找则,最前需加入“/”。
        2. 用这种方式,工作目录需为英文且不能有空格
 
2. 类加载器方式
 String filePath = XmlRead.class.getClassLoader().getResource("com/rgsc/xml/stu.xml") .getFile();
File f = new File(filePath );
注:1. 默认从类路径根目录查找,最前不需要加入“/”。
        2. 用这种方式,工作目录需为英文且不能有空格

 

Java从不同目录获取文件方式

原文:http://www.cnblogs.com/flykarry/p/4300761.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!