为此,我在谷歌上搜索了很长时间,但所有结果都指向 Java 7 之前的 NIO 解决方案。我用过 NIO stuff从文件系统的特定位置读取文件,这比以前容易得多 (Files.readAllBytes(path)
)。现在,我想读入打包在我的 WAR 和类路径中的文件。我们目前使用类似于以下的代码来做到这一点:
Input inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
/* iterate through the input stream to get all the bytes (no way to reliably find the size of the
* file behind the inputStream (see http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#available()))
*/
int byteInt = -1;
try
{
byteInt = inputStream.read();
while (byteInt != -1)
{
byteStream.write(byteInt);
byteInt = inputStream.read();
}
byteArray = byteStream.toByteArray();
inputStream.close();
return byteArray;
}
catch (IOException e)
{
//...
}
虽然这行得通,但我希望有一种更简单/更好的方法来处理 Java 7 中的 NIO 内容。我猜我需要得到一个 Path。在类路径上表示此路径的对象,但我不确定该怎么做。
如果这是一件 super 简单的事情,我深表歉意。我就是想不通。感谢您的帮助。
最佳答案
这对我有用。
import java.nio.file.Files;
import java.nio.file.Paths;
// fileName: foo.txt which lives under src/main/resources
public String readFileFromClasspath(final String fileName) throws IOException, URISyntaxException {
return new String(Files.readAllBytes(
Paths.get(getClass().getClassLoader()
.getResource(fileName)
.toURI())));
}
关于java - 使用 Java 7 NIO 从类路径读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14692600/