Web项目开发中,经常会有一些静态资源 , 被放置在resources目录下,随项目打包在一起,代码中要使用的时候,通过文件读取的方式,加载并使用;
今天总结整理了九种方式获取resources目录下文件的方法 。
其中公用的打印文件方法如下:
/*** 根据文件路径读取文件内容** @param fileInPath* @throws IOException*/public static void getFileContent(Object fileInPath) throws IOException {BufferedReader br = null;if (fileInPath == null) {return;}if (fileInPath instanceof String) {br = new BufferedReader(new FileReader(new File((String) fileInPath)));} else if (fileInPath instanceof InputStream) {br = new BufferedReader(new InputStreamReader((InputStream) fileInPath));}String line;while ((line = br.readLine()) != null) {System.out.println(line);}br.close();}
主要核心方法是使用getResource和getPath方法,这里的getResource("")里面是空字符串
 public void function1(String fileName) throws IOException {String path = this.getClass().getClassLoader().getResource("").getPath();//注意getResource("")里面是空字符串System.out.println(path);String filePath = path + fileName;System.out.println(filePath);getFileContent(filePath);}
主要核心方法是使用getResource和getPath方法,直接通过getResource(fileName)方法获取文件路径,注意如果是路径中带有中文一定要使用URLDecoder.decode解码 。
 /*** 直接通过文件名getPath来获取路径** @param fileName* @throws IOException*/public void function2(String fileName) throws IOException {String path = this.getClass().getClassLoader().getResource(fileName).getPath();//注意getResource("")里面是空字符串System.out.println(path);String filePath = URLDecoder.decode(path, "UTF-8");//如果路径中带有中文会被URLEncoder,因此这里需要解码System.out.println(filePath);getFileContent(filePath);}
直接通过文件名+getFile()来获取文件 。如果是文件路径的话getFile和getPath效果是一样的,如果是URL路径的话getPath是带有参数的路径 。如下所示:
url.getFile()=/admin/java/people.txt?id=5url.getPath()=/admin/java/people.txt使用getFile()方式获取文件的代码如下:
 /*** 直接通过文件名+getFile()来获取** @param fileName* @throws IOException*/public void function3(String fileName) throws IOException {String path = this.getClass().getClassLoader().getResource(fileName).getFile();//注意getResource("")里面是空字符串System.out.println(path);String filePath = URLDecoder.decode(path, "UTF-8");//如果路径中带有中文会被URLEncoder,因此这里需要解码System.out.println(filePath);getFileContent(filePath);}
推荐阅读
- Java:既然有了synchronized,为什么还要提供Lock?
 - 附:2种实现方式详细对比 Java 动态代理原理图解
 - 深度剖析Java的volatile实现原理,再也不怕面试官问了
 - 6 Java多线程:锁与AQS(下)
 - 三十九 Java开发学习----SpringBoot整合mybatis
 - JavaSPI详解
 - 幻塔斯帕克怎么获取
 - day04-JavaScript01
 - 未定事件簿此间怎么获取
 - 四 SoringCloud -微信获取用户信息
 
