小结从maven下resource文件夹读取文件的方法
在一个maven工程下,通常有resource文件夹,其中再存放相关的资源文件,
比如resource下有个files文件夹,其中有个文件叫test.txt,则读取方法之一为:
调用方法为:obj.getFile("file/test.txt") 传参的时候,最开始没有'/' ;
2 使用apache commons的io包:
可以看到apache commons io包真方便
在一个maven工程下,通常有resource文件夹,其中再存放相关的资源文件,
比如resource下有个files文件夹,其中有个文件叫test.txt,则读取方法之一为:
private String getFile(String fileName) {
StringBuilder result = new StringBuilder("");
/
ClassLoader classLoader = getClass().getClassLoader();
<span style="white-space:pre"> </span>//这一种直接得到的是File类型
File file = new File(classLoader.getResource(fileName).getFile());
<span style="white-space:pre"> </span>//这一种得到的是inputStream
<span style="white-space:pre"> </span>//isr=new InputStreamReader(CountMobileDictJob.class.getClassLoader().<span style="color:#ff0000;">getResourceAsStream(</span><span style="color: rgb(255, 0, 0); font-family: Arial, Helvetica, sans-serif;">fileName</span><span style="color: rgb(255, 0, 0); font-family: Arial, Helvetica, sans-serif;">);</span><span style="color:#ff0000;">
</span> 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包:
String result = "";
ClassLoader classLoader = getClass().getClassLoader();
try {
result = IOUtils.toString(classLoader.getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
可以看到apache commons io包真方便