我使用此测试将 txt 转换为 pdf:
package convert.pdf;
//getResourceAsStream(String name) : Returns an input stream for reading the specified resource.
//toByteArray : Get the contents of an InputStream as a byte[].
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import convert.pdf.txt.TextConversion;
public class TestConversion {
private static byte[] readFilesInBytes(String file) throws IOException {
return IOUtils.toByteArray(TestConversion.class.getResourceAsStream(file));
}
private static void writeFilesInBytes(byte[] file, String name) throws IOException {
IOUtils.write(file, new FileOutputStream(name));
}
//just change the extensions and test conversions
public static void main(String args[]) throws IOException {
ConversionToPDF algorithm = new TextConversion();
byte[] file = readFilesInBytes("/convert/pdf/text.txt");
byte[] pdf = algorithm.convertDocument(file);
writeFilesInBytes(pdf, "text.pdf");
}
}
问题:
Exception in thread "main" java.lang.NullPointerException at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1025) at org.apache.commons.io.IOUtils.copy(IOUtils.java:999) at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:218) at convert.pdf.TestConversion.readFilesInBytes(TestConversion.java:17) at convert.pdf.TestConversion.main(TestConversion.java:28)
I use the debugger, and the problem seems to be located here :
private static byte[] readFilesInBytes(String file) throws IOException {
return IOUtils.toByteArray(TestConversion.class.getResourceAsStream(file));
}
我的问题是什么?
最佳答案
听起来可能不存在具有该名称的资源。
您是否知道 Class.getResourceAsStream()
会找到与该类包相关的资源,而 ClassLoader.getResourceAsStream()
不会?您可以在 Class.getResourceAsStream()
中使用前导正斜杠来模仿这一点,因此
Foo.class.getResourceAsStream("/bar.png")
大致相当于
Foo.class.getClassLoader().getResourceAsStream("bar.png")
这实际上是您要加载的文件(即普通文件系统上的特定文件)吗?如果是这样,使用 FileInputStream
会是更好的选择。如果它是以其他方式捆绑在 jar 文件或类路径中的资源,请使用 Class.getResourceAsStream()
;如果它是可以位于文件系统中任何位置的任意文件,则使用 FileInputStream
。
编辑:另一件需要注意的事情,它之前给我带来了问题 - 如果这在你的开发箱上工作,恰好是 Windows,现在在生产服务器上失败,而生产服务器恰好是 Unix,请检查文件名的大小写。不同的文件系统以不同的方式处理区分大小写的事实可能是一个痛苦......
关于java - 为什么在尝试读取文件时会出现 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/703231/