是否有一种方法将资源中的文本文件读入字符串?
我想这是一个普遍的需求,但我在谷歌上找不到任何实用工具。
是否有一种方法将资源中的文本文件读入字符串?
我想这是一个普遍的需求,但我在谷歌上找不到任何实用工具。
当前回答
下面是一个使用Java 11的Files.readString的解决方案:
public class Utils {
public static String readResource(String name) throws URISyntaxException, IOException {
var uri = Utils.class.getResource("/" + name).toURI();
var path = Paths.get(uri);
return Files.readString(path);
}
}
其他回答
使用Apache commons的FileUtils。它有一个readFileToString方法
我创建了这样一个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
}
是的,Guava在Resources类中提供了这一点。例如:
URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);
如果你有番石榴,那么你可以使用:
String fileContent = Files.asCharSource(new File(filename), Charset.forName("UTF-8")).read();
(其他解决方案提到了番石榴的其他方法,但已弃用)
下面的代码对我有用:
compile group: 'commons-io', name: 'commons-io', version: '2.6'
@Value("classpath:mockResponse.json")
private Resource mockResponse;
String mockContent = FileUtils.readFileToString(mockResponse.getFile(), "UTF-8");