是否有一种方法将资源中的文本文件读入字符串?
我想这是一个普遍的需求,但我在谷歌上找不到任何实用工具。
是否有一种方法将资源中的文本文件读入字符串?
我想这是一个普遍的需求,但我在谷歌上找不到任何实用工具。
当前回答
Guava也有Files.readLines()如果你想要一个List<String>一行一行的返回值:
List<String> lines = Files.readLines(new File("/file/path/input.txt"), Charsets.UTF_8);
请参考这里比较3种方法(BufferedReader vs. Guava's Files vs. Guava's Resources)从文本文件中获取字符串。
其他回答
使用Apache commons的FileUtils。它有一个readFileToString方法
apache-commons-io有一个实用程序名为FileUtils:
URL url = Resources.getResource("myFile.txt");
File myFile = new File(url.toURI());
String content = FileUtils.readFileToString(myFile, "UTF-8"); // or any other encoding
下面是我的方法
public String getFileContent(String fileName) {
String filePath = "myFolder/" + fileName+ ".json";
try(InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)) {
return IOUtils.toString(stream, "UTF-8");
} catch (IOException e) {
// Please print your Exception
}
}
Guava也有Files.readLines()如果你想要一个List<String>一行一行的返回值:
List<String> lines = Files.readLines(new File("/file/path/input.txt"), Charsets.UTF_8);
请参考这里比较3种方法(BufferedReader vs. Guava's Files vs. Guava's Resources)从文本文件中获取字符串。
如果您想从项目资源(如文件)中获取String testcase / foo。Json在src/main/resources在你的项目,这样做:
String myString=
new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("testcase/foo.json").toURI())));
请注意,在其他一些示例中缺少getClassLoader()方法。