我收到 java.lang.NullPointerException,通常我可以毫无问题地找到罪魁祸首,但这次我很困惑。
首先我确认我的 JPQL 是这样工作的:
List<ShopOrder> shopOrders = poRepository.getShopOrder(id);
for (ShopOrder<?> order : shopOrders) {
System.out.println(order.toString());
在控制台中我得到了:
ShopOrder [po_id=2, po_number=323, po_due_date=2015-06-16, po_part_id=3, part_quantity=44, part_id=1, part_number=3241, part_decription=Train Hub, plasma_hrs=33.0000, gring_hours=10.0000, mill_hrs=2.0000, breakpress_hrs=4.0000]
ShopOrder [po_id=1, po_number=234, po_due_date=2015-06-09, po_part_id=1, part_quantity=3423, part_id=1, part_number=3241, part_decription=Train Hub, plasma_hrs=33.0000, gring_hours=10.0000, mill_hrs=2.0000, breakpress_hrs=4.0000]
然后我决定我需要一个更具体的错误。这是上面代码片段的完整方法:
@RequestMapping(value = "/generateShopOrder/{id}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public void generate(@PathVariable Long id) throws URISyntaxException {
System.out.println("po id to generate = " + id);
List<ShopOrder> shopOrders = poRepository.getShopOrder(id);
for (ShopOrder<?> order : shopOrders) {
System.out.println(order.toString());
try {
jobOrderGenerator = new JobOrderGenerator(shopOrders);
System.out.println("Printing inside try statement: PO number " + order.getPo_number() + "\nPrinting part id " + order.getPart_id());
} catch (InterruptedException exception) {
System.out.println("Something is null " + exception);
exception.printStackTrace();
} catch (IOException ex) {
System.out.print("Was not able to create job orders,IOexception " + ex);
} catch (InvalidFormatException e) {
System.out.print("Invalid file format: " + e);
}
}
但是,正如您在错误中看到的(发布在底部)仅打印出 println 语句“something null”。
然后我想也许我的文件出了问题,它在我的资源文件夹中,所以我通过执行以下操作检查了它:
public JobOrderGenerator(List<ShopOrder> shopOrder) throws InvalidFormatException, IOException, InterruptedException {
if(file.exists() && file.isDirectory()){
System.out.println("Was was found");
} else {
System.out.println("File was NOT found");
}
for (ShopOrder shopOrder1 : shopOrder) {
writeToSpecificCell(2, 1, sheetNumber, shopOrder1.getPo_number()); //Po Number
writeToSpecificCell(7, 3, sheetNumber, shopOrder1.getPo_number()); //Part Number
LocalDate date = shopOrder1.getPo_due_date();
String dateToString = date.toString();
writeToSpecificCell(1, 2, sheetNumber, dateToString); //Due_Date
writeToSpecificCell(7, 5, sheetNumber, Integer.toString(shopOrder1.getPart_quantity())); //Quantity
//writeToSpecificCell(1,2,sheetNumber, shopOrder.get); //Material
writeToSpecificCell(8, 3, sheetNumber, shopOrder1.getPart_decription()); //Part Description
//writeToSpecificCell(1,2,sheetNumber, shopOrder.getCustomer()); //Customer
writeToSpecificCell(10, 1, sheetNumber, shopOrder1.getMachine_number()); //Machine
sheetNumber++;
}
}
void writeToSpecificCell(int rowNumber, int cellNumber, int sheetNumber, String value) throws InvalidFormatException, IOException {
try {
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(sheetNumber);
XSSFRow row = sheet.getRow(rowNumber);
XSSFCell cell = row.createCell(cellNumber);
if (cell == null) {
cell = row.createCell(cellNumber);
}
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(value);
workbook.close();
} catch (IOException e) {
System.out.println("Error is writeToSpecificCell class " + e);
}
}
这告诉我它在构造函数中的 if 语句甚至没有被执行之前就失败了。这就是我想知道下一步该去哪里的地方。有什么建议吗?
错误:
Hibernate: select po0_.id as col_0_0_, po0_.po_number as col_1_0_, po0_.due_date as col_2_0_, partlist1_.id as col_3_0_, partlist1_.part_quantity as col_4_0_, part2_.id as col_5_0_, part2_.part_number as col_6_0_, part2_.part_description as col_7_0_, part2_.plasma_hrs_per_part as col_8_0_, part2_.grind_hrs_per_part as col_9_0_, part2_.mill_hrs_per_part as col_10_0_, part2_.brakepress_hrs_per_part as col_11_0_ from T_PO po0_ inner join T_PO_PART partlist1_ on po0_.id=partlist1_.po_id inner join T_PART part2_ on partlist1_.part_id=part2_.id where po0_.id=?
Hibernate: select po0_.id as col_0_0_, po0_.po_number as col_1_0_, po0_.due_date as col_2_0_, partlist1_.id as col_3_0_, partlist1_.part_quantity as col_4_0_, part2_.id as col_5_0_, part2_.part_number as col_6_0_, part2_.part_description as col_7_0_, part2_.plasma_hrs_per_part as col_8_0_, part2_.grind_hrs_per_part as col_9_0_, part2_.mill_hrs_per_part as col_10_0_, part2_.brakepress_hrs_per_part as col_11_0_ from T_PO po0_ inner join T_PO_PART partlist1_ on po0_.id=partlist1_.po_id inner join T_PART part2_ on partlist1_.part_id=part2_.id where po0_.id=?
ShopOrder [po_id=2, po_number=323, po_due_date=2015-06-16, po_part_id=3, part_quantity=44, part_id=1, part_number=3241, part_decription=Train Hub, plasma_hrs=33.0000, gring_hours=10.0000, mill_hrs=2.0000, breakpress_hrs=4.0000]
ShopOrder [po_id=1, po_number=234, po_due_date=2015-06-09, po_part_id=1, part_quantity=3423, part_id=1, part_number=3241, part_decription=Train Hub, plasma_hrs=33.0000, gring_hours=10.0000, mill_hrs=2.0000, breakpress_hrs=4.0000]
[ERROR] com.htd.aop.logging.LoggingAspect - Exception in com.htd.web.rest.PoResource.generate() with cause = null
java.lang.NullPointerException: null
at com.htd.domain.JobOrderGenerator.<init>(JobOrderGenerator.java:19) ~[classes/:na]
at com.htd.web.rest.PoResource.generate(PoResource.java:302) ~[classes/:na]
at com.htd.web.rest.PoResource$$FastClassBySpringCGLIB$$cfcd338a.invoke(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.1.6.RELEASE.jar:4.1.6.RELEASE]
------------更新--------
@Aspect
public class LoggingAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Inject
private Environment env;
@Pointcut("within(com.htd.repository..*) || within(com.htd.service..*) || within(com.htd.web.rest..*)")
public void loggingPointcut() {}
@AfterThrowing(pointcut = "loggingPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause(), e);
} else {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause());
}
}
--------更新2------------
这是执行错误的语句:
if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause(), e);
------------更新3------------ 我这样做是为了检查 Environment 是否为空,但我在控制台中没有看到任何内容。
@AfterThrowing(pointcut = "loggingPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (this.env==null){
log.error("Environment is null");
}
------------更新4------------
ClassLoader classLoader = getClass().getClassLoader();
这就是返回 java.lang.NullPointerException 的原因,它甚至从未到达:
file = new File(classLoader.getResource("Shop-Order.xlsx").getFile());
这就是我无法检查文件是否为空的原因。仍在研究原因。一旦我解决了这个问题,我可能需要更改这篇文章的标题。
------------更新 5------------
我需要它,因为它在我的资源文件中,该文件将在我的 jar 文件中。我将写入文件(文件中的文件)
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("Shop-Order.xlsx");
现在我必须弄清楚如何将其作为文件传递给 apache poi
XSSFWorkbook workbook = new XSSFWorkbook(file);
它需要一个文件,而不是输入流。
------------更新6----------------
在我完成更新 6 后,我能够找出失败的原因。下面的方法。在控制台中打印:
Inside writeToSpecificCell before try statement 2 0 123
和
Inside writeToSpecificCell at the beginning of try statement
void writeToSpecificCell(int rowNumber, int cellNumber, int sheetNumber, String value) throws InvalidFormatException, IOException {
System.out.println("Inside writeToSpecificCell before try statement "+cellNumber+" "+sheetNumber+" "+value);
try {
System.out.println("Inside writeToSpecificCell at the beginnning of try statement");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheetAt(sheetNumber);
XSSFRow row = sheet.getRow(rowNumber);
XSSFCell cell = row.createCell(cellNumber);
if (cell == null) {
cell = row.createCell(cellNumber);
}
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(value);
System.out.println("Inside writeToSpecificCell at the end of try statement");
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
无法确定,因为源代码未完全显示,但 file
为 null 似乎合乎逻辑。它是构造函数中第一个输出之前唯一引用的东西。
试试这个
if (file == null) {
System.out.println("file is null");
} else if (file.exists() && file.isDirectory()){
System.out.println("Was was found");
} else {
System.out.println("File was NOT found");
}
通常,要解决这些问题,您只需要查看堆栈跟踪,它会立即告诉您问题出在哪里。如果这不起作用,正如@AndreasAumayr 所建议的那样,使用调试器并中断异常(图标看起来像“J!”)或堆栈跟踪中提到的行。
关于尝试写入 excel 文件时出现 java.lang.NullPointerException :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30900212/