Удаление файла не работает - это работает только один раз после перезапуска сервера Jboss и в режиме отладки

Я разрабатываю систему с использованием Struts 1.x, JspServlet а также Pentaho(генерация отчета).

Здесь, когда после генерации отчета пользователь может открыть и сохранить этот файл как Excel, и это работает нормально.

Но проблема возникает, когда открыть файл, он создает файл в нашей временной папке jboss, что файл не удаляется - это проблема.

мы удаляем файл с уровня кода и выясняем, что после перезапуска сервера после первого раза он удаляется, а при отладке - каждый раз, когда он удаляется.

public Object process() throws RenderException, IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    // properties for XSSF
    File xmlFile = null;
    File templateFile = null;
    Writer xmlWriter = null;
    boolean isXLSX = false;
    timeStamp = Calendar.getInstance().getTimeInMillis();

    try {
        OutputType outputType = rendererAttrList.getOutputType();

        Frame[] frameList = xmlDef.getShownFrames(renderDocs);
        if (frameList != null) {
            // ==============================================TPID#65448 code
            // add========================================
            boolean isPentahoExcel = false;
            Frame t_CurrFrame = frameList[0];

            if (t_CurrFrame != null) {

                FrameType frameType = t_CurrFrame.getFrameType();
                if (frameType == FrameType.FRAME_TYPE_EXTERNAL) {
                    isPentahoExcel = true;
                }
            }
            // ==============================================TPID#65448 code end========================================

            isXLSX = isXLSXOutput(frameList);

            // native excel support and if the output is not supported by
            // .xls, change the output to .xlsx
            if (((outputType == OutputType.NATIVE_EXCEL2007) || ((outputType == OutputType.NATIVE_EXCEL97) && isXLSX))&&!isPentahoExcel)
                     {
                workbook = new XSSFWorkbook();
                rendererAttrList.setOutputType(OutputType.NATIVE_EXCEL2007);

                xmlFile = File.createTempFile(getXmlDef().getName()
                        + timeStamp, ".xml");

                logger.info("XML File location :"
                        + xmlFile.getAbsolutePath());

                xmlWriter = new OutputStreamWriter(new FileOutputStream(
                        xmlFile), "UTF-8");
                spreadSheetWriter = new SpreadsheetWriter(xmlWriter);

                spreadSheetWriter.beginSheet();
            } else {
                workbook = new HSSFWorkbook();
            }


                dataFormat = workbook.createDataFormat();
                sheet = workbook.createSheet("Report");
                logger.debug("Start rendering the excel output in "
                        + rendererAttrList.getOutputType() + " format ");
                renderOutput();
                logger.debug("Stop rendering the excel output ");

            if (workbook instanceof HSSFWorkbook) {
                // ==============================================TPID#65448 code add========================================

                if (isPentahoExcel) {

                    renderExternalXLSX(t_CurrFrame,byteArrayOutputStream);


                } else {
                    autoSizeColumn();
                    // write the excel to output
                    workbook.write(byteArrayOutputStream);
                }

                // ==============================================TPID#65448 code end========================================
            } else {
                // 1. generate data in XML format
                spreadSheetWriter.endSheet();

                // close the xml stream before we substitute in xlsx file
                try {
                    if (xmlWriter != null)
                        xmlWriter.close();

                    xmlWriter = null;
                } catch (Exception ex) {
                    logger.error("Error while closing xmlWriter for file "
                            + xmlFile.getName());
                }

                // Step 2. create template from the excel workbook
                String sheetRef = ((XSSFSheet) sheet).getPackagePart()
                        .getPartName().getName();
                templateFile = createTemplate();

                ByteArrayOutputStream xlsxOutput = new ByteArrayOutputStream();

                // Step 3. Substitute the template entry with the generated
                // data
                substitute(templateFile, xmlFile, sheetRef.substring(1),
                        xlsxOutput);

                // if the data is too large don't try to auto size the
                // columns
                // may result into out of memory exception
                if (!isXLSX) {
                    // autosize the columns
                    InputStream inp = new ByteArrayInputStream(
                            xlsxOutput.toByteArray());

                    workbook = WorkbookFactory.create(inp);
                    sheet = workbook.getSheetAt(0);
                    autoSizeColumn();

                    if (xlsxOutput != null)
                        xlsxOutput.close();

                    byteArrayOutputStream = new ByteArrayOutputStream();

                    workbook.write(byteArrayOutputStream);
                    inp.close();
                    xlsxOutput.close();
                } else {
                    byteArrayOutputStream = xlsxOutput;
                }
            }
        }
    } catch (Exception de) {
        logger.error(de.getMessage(), de);

        throw new RenderException(de.getMessage());
    } finally {
        try {


            if (xmlWriter != null)
                xmlWriter.close();

            if (xmlFile != null)
                xmlFile.delete();

            if (templateFile != null){

                    templateFile.delete();                                                      

            }




        } catch (Exception ex) {
            logger.error("Error while closing xmlWriter for file "
                    + xmlFile.getName());
        }
    }

    return byteArrayOutputStream;
}

Резюме моего вопроса - когда Jboss затем перезапустите в первый раз и при отладке временно созданный файл (временный каталог) удаляется успешно.

но когда он работает нормально, он не удаляет файл

но каждый раз, когда он вызывает определенный уровень кода, проблема заключается в том, почему он не работает.

templateFile.delete();  

Большое спасибо...

1 ответ

Что происходит, когда delete метод называется? Вы можете записать вывод метода "delete", чтобы увидеть результат. Так должно быть true или же false, Это исключение? Метод удаления может бросить SecurityException указывая, что вам отказано в доступе к удалению файла.

В общем, первое, что нужно сделать, это попытаться понять, почему файл не удаляется, учитывая набор инструментов, предоставленный вам этой конкретной функцией.

Другим подходом может быть также вызов метода deleteIfExists вместо этого. Смотрите здесь: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html

Другие вопросы по тегам