尝试写入excel文件时java.lang.NullPointerException:

时间:2015-06-17 19:02:48

标签: java spring-mvc

我收到了一个java.lang.NullPointerException,通常我没有找到罪魁祸首的问题,但这次我很困惑。

首先我确认我的JPQL工作原理如下:

$('#circle').circleProgress({
    startAngle: 90,
    size: 240,
    thickness: 22,
    fill: { gradient: [['#0681c4', .5], ['#4ac5f8', .5]], gradientAngle: Math.PI / 4 }
}).on('circle-animation-progress', function(event, progress, stepValue) {
    $(this).find('strong').text(String(stepValue.toFixed(2)).substr(2)+'%');
});

在控制台中我得到了:

   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]

但是,正如您在错误中看到的那样(在底部发布)只打印出println语句,说“null null”。

然后我想也许我的文件中有一些东西正在我的资源文件夹中,所以我通过执行以下操作检查了它:

@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);

            }
        }

这告诉我在构造函数中的if语句甚至没有执行之前它失败了。这是我想知道下一步该去哪里的地方。有什么建议吗?

错误:

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);
        }
    }

----------- ---------更新

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]

---------更新2 ------------

这是执行错误的语句:

@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());
        }
    }

-----------更新3 ------------ 我这样做是为了检查Environment是否为null并且我在控制台中没有看到任何内容。

if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) {
            log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
                    joinPoint.getSignature().getName(), e.getCause(), e);

-------------更新4 ------------

@AfterThrowing(pointcut = "loggingPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {

        if (this.env==null){
            log.error("Environment is null");
        }

这就是返回java.lang.NullPointerException的东西,它甚至都没有:

ClassLoader classLoader = getClass().getClassLoader();

这就是我无法检查文件是否为空的原因。仍在调查为什么。一旦我解决这个问题,我可能需要更改这篇文章的标题。

----------更新5 --------------

我需要这个,因为它在我的资源文件中,它将在我的jar文件中。我将写入文件(文件中的文件)

file = new File(classLoader.getResource("Shop-Order.xlsx").getFile());

现在我必须弄清楚如何将此文件作为文件传递给apache poi

inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("Shop-Order.xlsx");

它需要一个文件,而不是输入流。

----------更新6 ---------------

在我完成更新6之后,我能够找出失败的原因。以下方法。在控制台中打印:

XSSFWorkbook workbook = new XSSFWorkbook(file);

Inside writeToSpecificCell before try statement 2 0 123

1 个答案:

答案 0 :(得分:1)

无法确定,因为源未完全显示,但file为空似乎合乎逻辑。它是构造函数中第一个输出之前引用的唯一内容。 试试这个

    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!”)上或在堆栈跟踪中提到的行上中断。