您的位置:首页 > 编程语言 > Java开发

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

2015-02-26 10:36 197 查看
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. 用这种方式,工作目录需为英文且不能有空格
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: