1, src / main / java files compiled under question
Maven configuration is required, otherwise the configuration files in src / main / java will not be compiled.
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.txt</include>
</includes>
</resource>
</resources>
2, read the file: 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, read the file: spring of ClassPathResource
//此处全部是相对于 classpath 路径的
ClassPathResource resource = new ClassPathResource("templates/file-resource2.txt");
4, read the properties file: Classpath based
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, reads the properties file: Use 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"));
}