【问题标题】:report is downloaded in a different name while using JasperReports使用 JasperReports 时以不同的名称下载报告
【发布时间】:2015-01-19 12:12:55
【问题描述】:

我正在使用此代码从报告“jrxml”生成 pdf 文件,但生成的 pdf 文件名称中带有数字。例如

joelle8172361278631763.pdf 你能帮我解决这个问题吗

public String showReport () throws JRException, FileNotFoundException, IOException {
        File pdf = File.createTempFile("joelle", ".pdf");
        FileOutputStream out = new FileOutputStream(pdf) ;          
        initConnection();
        String reportName = "C:\\folder\\Outgoings.jrxml";

        JasperDesign jasperDesign = null;
        try {
            jasperDesign = JRXmlLoader.load( reportName);
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, conn);

            JasperExportManager.exportReportToPdfStream(jasperPrint, out);
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (JRException e) {
                    System.out.println("catch2");
            e.printStackTrace();
        }
return null ; }

【问题讨论】:

    标签: java jasper-reports


    【解决方案1】:

    不是 JasperReports 框架本身导致名称发生变化,而是标准 SDK 调用 File.createTempFile("joelle", ".pdf"); 诉诸 File.generateFile 将随机数附加到文件名以确保其唯一性:

    private static File generateFile(String prefix, String suffix, File dir)
            throws IOException
        {
            long n = LazyInitialization.random.nextLong();
            if (n == Long.MIN_VALUE) {
                n = 0;      // corner case
            } else {
                n = Math.abs(n);
            }
            return new File(dir, prefix + Long.toString(n) + suffix);
        }
    

    关于如何在不修改名称的情况下创建临时文件,请参阅此主题:How to create a temp file in java without the random number appended to the filename?

    【讨论】:

    • 我已经阅读了,但我并没有真正理解……接下来如何处理 tDir ?
    • 这实际上取决于您希望如何处理这些临时文件的创建。例如,您可以首先尝试通过调用File.exists 方法来确定给定文件是否已经存在,然后在必要时将其删除。您也可以考虑使用File.deleteOnExit() 在进程终止时自动丢弃它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多