1、src/main/java 下文件编译问题
需要进行 maven 的配置,否则 src/main/java 下的配置文件不会被编译。
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.txt</include>
</includes>
</resource>
</resources>
2、读取文件: getResource
//相对路径
//file.txt 在当前代码类的相对路径下去找
//如:D:/work/blog-test/target/classes/com/vim/test/file.txt
String path = this.getClass().getResource("file.txt").getPath();
//绝对路径
//file.txt 在当前 classpath 下已绝对路径去找
//如:D:/work/blog-test/target/classes/txt/file.txt
String path = this.getClass().getResource("/txt/file.txt").getPath();
3、读取文件: spring 的 ClassPathResource
//此处全部是相对于 classpath 路径的
ClassPathResource resource = new ClassPathResource("templates/file-resource2.txt");
4、读取 properties 文件: 基于 Classpath
public void test001() throws Exception{
InputStream in = this.getClass().getResourceAsStream("/test.properties");
Properties properties = new Properties();
properties.load(in);
System.out.println(properties.getProperty("user"));
}
5、读取 properties 文件: 使用 ResourceBundle
public void test001() throws Exception{
ResourceBundle resource = ResourceBundle.getBundle("test");
System.out.println(resource.getString("user"));
}
public void test001() throws Exception{
InputStream in = this.getClass().getResourceAsStream("/test.properties");
ResourceBundle resource = new PropertyResourceBundle(in);
System.out.println(resource.getString("user"));
}