是否有一种方法将资源中的文本文件读入字符串?
我想这是一个普遍的需求,但我在谷歌上找不到任何实用工具。
是否有一种方法将资源中的文本文件读入字符串?
我想这是一个普遍的需求,但我在谷歌上找不到任何实用工具。
当前回答
如果你有番石榴,那么你可以使用:
String fileContent = Files.asCharSource(new File(filename), Charset.forName("UTF-8")).read();
(其他解决方案提到了番石榴的其他方法,但已弃用)
其他回答
我创建了这样一个NO-dependency静态方法:
import java.nio.file.Files;
import java.nio.file.Paths;
public class ResourceReader {
public static String asString(String resourceFIleName) {
try {
return new String(Files.readAllBytes(Paths.get(new CheatClassLoaderDummyClass().getClass().getClassLoader().getResource(resourceFIleName).toURI())));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class CheatClassLoaderDummyClass{//cheat class loader - for sql file loading
}
使用Apache commons的FileUtils。它有一个readFileToString方法
对于java 7:
new String(Files.readAllBytes(Paths.get(getClass().getResource("foo.txt").toURI())));
对于Java 11:
Files.readString(Paths.get(getClass().getClassLoader().getResource("foo.txt").toURI()));
下面是我的方法
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
}
}
如果你有番石榴,那么你可以使用:
String fileContent = Files.asCharSource(new File(filename), Charset.forName("UTF-8")).read();
(其他解决方案提到了番石榴的其他方法,但已弃用)