Summary

  • read resources
  • io
  • IOUtils

1. read resources

如读取resources/file/test.xml

method 1

1
2
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());

method2

1
2
ClassLoader classLoader = 类名.class.getClassLoader();
InputStream in = classLoader.getResourceAsStream("file/test.xml");

3.IOUtils

1
2
3
4
5
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.io</artifactId>
<version>2.4</version>
</dependency>

usage:

1
2
3
4
5
6
7
8
9
10
11
12
private String getFileWithUtil(String fileName) {

String result = "";

ClassLoader classLoader = getClass().getClassLoader();
try {
result = IOUtils.toString(classLoader.getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
return result;
}