是否有一种方法将资源中的文本文件读入字符串?
我想这是一个普遍的需求,但我在谷歌上找不到任何实用工具。
是否有一种方法将资源中的文本文件读入字符串?
我想这是一个普遍的需求,但我在谷歌上找不到任何实用工具。
当前回答
至少在Apache common -io 2.5中,IOUtils.toString()方法支持URI参数,并返回位于类路径上的jar中的文件内容:
IOUtils.toString(SomeClass.class.getResource(...).toURI(), ...)
其他回答
如果你有番石榴,那么你可以使用:
String fileContent = Files.asCharSource(new File(filename), Charset.forName("UTF-8")).read();
(其他解决方案提到了番石榴的其他方法,但已弃用)
是的,Guava在Resources类中提供了这一点。例如:
URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);
我使用以下从类路径读取资源文件:
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;
public class ResourceUtilities
{
public static String resourceToString(String filePath) throws IOException, URISyntaxException
{
try (InputStream inputStream = ResourceUtilities.class.getClassLoader().getResourceAsStream(filePath))
{
return inputStreamToString(inputStream);
}
}
private static String inputStreamToString(InputStream inputStream)
{
try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"))
{
return scanner.hasNext() ? scanner.next() : "";
}
}
}
不需要第三方依赖。
使用Apache commons的FileUtils。它有一个readFileToString方法
yegor256用Apache Commons IO找到了一个很好的解决方案:
import org.apache.commons.io.IOUtils;
String text = IOUtils.toString(this.getClass().getResourceAsStream("foo.xml"),
"UTF-8");