在maven工程中,我们会将配置文件放到,src/main/resources 下面,例如

我们需要确认resource 下的文件 编译之后存放的位置


它编译的路径直接位于classes下面,这个路径其实就是classPath的路径,所以,在resources 根目录下的配置文件其实就是 classPath的路径:
- public static void main(String[] args) throws ParserConfigurationException, Exception{
- ClassLoader classLoader = TestDom.class.getClassLoader();
- URL resource = classLoader.getResource("test.xml");
- String path = resource.getPath();
- System.out.println(path);
- InputStream resourceAsStream = classLoader.getResourceAsStream("test.xml");
在一个maven工程下,通常有resource文件夹,其中再存放相关的资源文件,
比如resource下有个files文件夹,其中有个文件叫test.txt,则读取方法之一为:
Java代码 收藏代码
private String getFile(String fileName) {
StringBuilder result = new StringBuilder("");
/
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
调用方法为:obj.getFile("file/test.txt")
2 使用apache commons的io包:
Java代码 收藏代码
String result = "";
ClassLoader classLoader = getClass().getClassLoader();
try {
result = IOUtils.toString(classLoader.getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
可以看到apache commons io包真方便
本文介绍了在Maven项目中如何处理资源文件的路径问题,包括如何读取src/main/resources目录下的配置文件,并展示了两种实用的方法:通过Java类加载器获取资源路径及使用Apache Commons IO库简化文件读取。
2659

被折叠的 条评论
为什么被折叠?



