在java中读取读取文件,常常由于路径的问题找不到,此文用于记录如何定位文件的简单方法。java
本基于springboot作的测试,主要是构建工程方便,所用的方法都是JDK中的方法,主要测试有”/“和没有""的问题,以及getResourceAsStream(String string)
和getResource(String string)
的问题。spring
解释一下,主要有两个配置文件,a.properties
和b.properties
,a.properties
方法java的代码里,b.properties
放在resources的配置目录中。springboot
编译以后,classpath
的路径为:target/classes
,斜线"/"指的也是这个路径,全部,若是有斜线就会去这个路径下面去找,若是没有斜线,就会去那个类的当前坐在路径去找。测试
public class TestPath { public static void main(String[] args) { TestPath t = new TestPath(); //在当前TestPath类所在的包查询 InputStream a = t.getClass().getResourceAsStream("a.properties"); //在classpath路径下进行查询 InputStream b = t.getClass().getResourceAsStream("/b.properties"); //在当前TestPath类所在的包查询 URL url_a = t.getClass().getResource("a.properties"); //在classpath路径下进行查询 URL url_b = t.getClass().getResource("/b.properties"); System.out.println(); } }
以上,两个方法均可以用来定位文件,区别有两个:url
getResourceAsStream()
返回的是InputStream
,能够直接读取。getResource()
返回的是URL对象,方便获取文件的path路径。