我正在使用 iText DITO SDK 使用 JSON 创建 PDF,并使用 Core Java 应用程序创建 DITO 文件,但在以下源代码中出现 NullPointer 异常:
PdfProducer.convertTemplateFromPackage(templatePackageFile, templateName, fos, new JsonData(json));
在调试代码时,我观察到 filePath 为 null 但路径有值。这可能是 NullPointerException 的可能原因吗?
templatePackage 文件和 templateName 示例名称应该是什么?
PDF 正在路径
C:/output/New.pdf
生成,但已损坏 (0 KB)。
代码片段:
String inputSourcePath = "C:\\output\\";
final File templatePackageFile = new File(inputSourcePath);
final String templateName = "invoice.dito";
final FileOutputStream fos = new FileOutputStream(new File("C:/output/New.pdf"));
final String json="{\r\n" + " \"first_name\": \"Alexey\",\r\n"
+ " \"last_name\": \"Subach\",\r\n"
+ " \"email\": \"[email protected]\",\r\n"
+ " \"address\": \"Minsk, Belarus\",\r\n"
+ " \"items\": [\r\n"
+ " {\"item\": \"iText Core Production\", \"price\": \"1000\", \"quantity\": \"13\"},\r\n"
+ " {\"item\": \"iText Core QA\", \"price\": \"999\", \"quantity\": \"1\"},\r\n"
+ " {\"item\": \"iText Core Development\", \"price\": \"999\", \"quantity\": \"100\"},\r\n"
+ " {\"item\": \"iText Lego pack Star Wars\", \"price\": \"10\", \"quantity\": \"20\"},\r\n"
+ " {\"item\": \"iText Lego pack Harry Potter\", \"price\": \"20\", \"quantity\": \"15\"}\r\n"
+ " ]\r\n"
+ "}";
PdfProducer.convertTemplateFromPackage(templatePackageFile, templateName, fos, new JsonData(json));
在调试代码时,我观察到 filePath 为 null 但路径有值。这可能是 NullPointerException 的可能原因吗?
没有。
看看
java.io.File
来源:
// -- Integration with java.nio.file --
private transient volatile Path filePath;
...
public Path toPath() {
Path result = filePath;
if (result == null) {
synchronized (this) {
result = filePath;
if (result == null) {
result = FileSystems.getDefault().getPath(path);
filePath = result;
}
}
}
return result;
}
因此,
filePath
仅用于缓存与所讨论的Path
对象相对应的File
对象。而只要没有为 Path
实例检索到 File
对象,自然就是 null
。
要找到
NullPointerException
的原因,您最好检查该异常的堆栈跟踪以查明抛出该异常的位置。