本文着重讨论路径和文件的关系,不考虑获取文件前后的处理。
读取后输出文件内容的方法:
private void printFileContent(File file) {
InputStream in;
try {
// 一次读一个字节
System.out.println("---按字节读取,路径为:" + file.getAbsolutePath() + "---");
in = new FileInputStream(file);
int bytes;
while ((bytes = in.read()) != -1) {
System.out.write(bytes);
}
System.out.println("n---读取完毕!---");
in.close();
} catch (IOException e) {
System.out.println("读取文件失败!");
e.printStackTrace();
}
}
绝对路径
public void absolutePath() {
File file = new File("D:\myFile.txt");
printFileContent(file);
}
输出:
总结---按字节读取,路径为:D:myFile.txt---
this is a test file!
---读取完毕!---
绝对路径读取除了本地调试外,并不推荐使用。开发环境大部分是linux,迁移后绝对路径需要修改,比较繁琐。
相对路径相对路径读取基本都是把文件放到resource目录下,获取编译后的文件
ClassPathResource: public void classPathResource() throws IOException {
File file = new ClassPathResource("myFile.txt").getFile();
printFileContent(file);
}
输出:
getResource和getResourceAsStream:---按字节读取,路径为:D:1-project6.ad-shiningtargetclassesmyFile.txt---
this is a test file!
---读取完毕!---
public void getResource() throws IOException {
File file = new File(this.getClass().getClassLoader().getResource("myFile.txt").getFile());
printFileContent(file);
}
输出同上
这里需要注意两点:
1.getClassLoader()可以省略,省略后的文件路径需要在开头加"/"。如:
File file = new File(this.getClass().getResource("/myFile.txt").getFile());
其实,class.getResource("/") == class.getClassLoader().getResource("")
Class.getResource和ClassLoader.getResource本质上是一样的,都是使用ClassLoader.getResource加载资源的。
2.可以直接用getResourceAsStream()获取InputStream流对象(推荐)
相当于你用getResource()取得File文件后,再new InputStream(file)一样的结果
InputStream in = this.getClass().getResourceAsStream("/myFile.txt");
FileSystemResource:
public void FileSystemResource() throws IOException {
File file = new FileSystemResource("src/main/resources/myFile.txt").getFile();
printFileContent(file);
}
输出:
---按字节读取,路径为:D:1-project6.ad-shiningsrcmainresourcesmyFile.txt---
this is a test file!
---读取完毕!---
可以看到这种方法获取的就是项目下的原文件。根目录就是项目根目录
总结ClassPathResource,getResource,getResourceAsStream都是以编译后的classes作为根目录,读取的是经过编译后存放的文件,而FileSystemResource是以项目根目录来读取原文件
打包运行后的效果 绝对路径:此为window环境所以不修改路径可以成功,如果是其他环境必须修改成对应绝对路径才行
用ClassPathResource读取失败: 用getResource读取失败: 用FileSystemResource读取失败: 用getResourceAsStream读取成功: public void getResourceAsStream() throws IOException {
InputStream in = this.getClass().getResourceAsStream("/myFile.txt");
printFileStream(in);
}
用ClassPathResource.getInputStream()读取成功:
public void classPathResourceStream() throws IOException {
InputStream in = new ClassPathResource("myFile.txt").getInputStream();
printFileStream(in);
}
输出同上
总结显然,打包后文件路径已失效,只能以流的形式读取存放在jar包中的文件,综合考虑建议使用:
this.getClass().getResourceAsStream("/" + 文件名);
this.getClass.getClassLoader.getResourceAsStream(文件名);
new ClassPathResource(文件名).getInputStream();
本文参考了以下文章:
http://blog.sina.com.cn/s/blog_4b5bc0110100g22w.html;
https://www.cnblogs.com/yadongliang/p/7920053.html



