零、本文由来
感觉从业这么久以来,读取文件路径相关问题一直是一个痛
用的很少,之前也解决过相关的问题
但是得用这种路径
1
| src/test/resources/test/test.txt
|
上面这种路径如果在代码中的话,src/test/resources是不会存在的,会出现问题
本次学到了一个新的方法,Class.getResourceAsStream();
需要的路径在资源文件夹下面即可,填写路径:/test/test.txt
打包最终的路径会在:WEB-INF/classes/test/test.txt
ps:因maven打包配置不同,最终resources资源文件夹下的路径是不同的,注意src的坑即可
一、文件结构
1 2 3 4 5 6 7
| │ └── test │ ├── java │ │ └── mq │ │ └── Test.java │ └── resources │ ├── test │ │ └── test.txt
|
二、读取代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @RunWith(value = SpringJUnit4ClassRunner.class) @ContextConfiguration({"/spring-config.xml"}) public class Test { @Test public void test() throws IOException { InputStream inputStream = Test.class.getResourceAsStream("/test/test.txt"); byte[] buffer = new byte[1024]; int len; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); String res = bos.toString(); System.out.println(res); } }
|