在一个maven工程下,通常有resource文件夹,其中再存放相关的资源文件,
比如resource下有个files文件夹,其中有个文件叫test.txt,则读取方法之一为:
调用方法为:obj.getFile("file/test.txt")
2 使用apache commons的io包:
可以看到apache commons io包真方便
比如resource下有个files文件夹,其中有个文件叫test.txt,则读取方法之一为:
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包:
String result = "";
ClassLoader classLoader = getClass().getClassLoader();
try {
result = IOUtils.toString(classLoader.getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
可以看到apache commons io包真方便