【问题标题】:Is there a way to delete the PDF byte array and html file? [duplicate]有没有办法删除 PDF 字节数组和 html 文件? [复制]
【发布时间】:2021-10-24 05:46:12
【问题描述】:

我正在尝试在生成字节数组 PDF 和 HTML 文件后将其删除,并将 PDF 保存到字节数组 Document 以节省服务器空间使用。 Writer 类和 pdf 字节数组没有删除方法。如果有人可以帮助我解决这个问题,我们将不胜感激。

// File output
Writer file = new FileWriter (new File("src/" + "xyz.html"));
template.process(data, file);
file.flush();
file.close();

HtmlConverter.convertToPdf(new FileInputStream("src/" + "xyz.html"),new FileOutputStream("src/" + "XYZ.pdf"));

Path pdfPath = Paths.get("src/" + "XYZ.pdf");
byte[] pdf = Files.readAllBytes(pdfPath);

byteDocument = pdf;
 
//Delete pdf and html files.

【问题讨论】:

  • 您无需执行任何操作即可删除它们。如果您停止使用它们,垃圾收集器将摆脱它们。 Java 没有或不需要删除方法。

标签: java file writer


【解决方案1】:

如果您有足够的 RAM 来保存 PDF,那么您很可能同时有足够的内存来存储源 HTML。在这种情况下,完全跳过文件系统:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(buffer);
template.process(data, writer);
writer.flush();

ByteArrayInputStream input = new ByteArrayInputStream(buffer.toByteArray());
buffer.reset();
HtmlConverter.convertToPdf(input, buffer);

byteDocument = buffer.toByteArray();

如果由于内存限制需要使用文件系统,请使用Files.delete() 删除临时文件。

【讨论】:

  • 谢谢,我使用 Files.delete() 删除临时文件
猜你喜欢
  • 1970-01-01
  • 2018-12-14
  • 2021-01-22
  • 1970-01-01
  • 2021-12-03
  • 2011-05-26
  • 2018-04-18
  • 2014-04-17
  • 2021-09-12
相关资源
最近更新 更多