java - 如何将 System.setProperty 的范围限制为仅设置它的方法?

标签 java

我正在进行导出,要求将文件存储在 tmp 文件夹内的文件夹中,并且对于不同的导出,每个文件夹必须不同。

所以我的export()方法执行以下操作:

System.setProperty("java.io.tmpdir", System.getProperty("java.io.tmpdir")+pathSpecificToFirstExport);

createTempFile 方法使用 System.getProperty("java.io.tmpdir")将文件存储在其中。

当上述方法运行时,再次调用export()设置新的System.getProperty("java.io.tmpdir")System.getProperty("java.io.tmpdir")+pathSpecificToFirstExport+pathSpecificToSecondExport而我真正想要的只是 System.getProperty("java.io.tmpdir")+pathSpecificToSecondExport .

我无法硬编码 System.getProperty("java.io.tmpdir")而不是每次都向其附加新路径 System.getProperty("java.io.tmpdir")针对不同环境的变化。我无法更改临时文件的创建方式,因为它不是由我完成的,而是由 write() 完成的。的SXSSFWorkbook.java :

File tmplFile = TempFile.createTempFile("poi-sxssf-template", ".xlsx");

我正在寻找的是限制 System.getProperty("java.io.tmpdir") 的范围仅适用于方法 export() 的实例

有什么想法吗?

最佳答案

你不能这么做。 System 属性对象实际上是全局的,并且没有适用于它的作用域机制。

您需要做的是使用不同的机制来创建不依赖于“java.io.tmpdir”的临时文件。解决方案:使用createTempFile(String prefix, String suffix, File Directory),并使用(例如)线程局部变量跟踪“当前”临时目录。

更好的是,使用 java.nio.Files 中的等效方法。

<小时/>

Unfortunately I cannot make the above change since the createTempDirectory is done by another method that I cannot change (SXSSFWorkbook does that for me).

所以我看了一下SXSSFWorkbook,这是它创建临时文件的地方:

/**
 * Write out this workbook to an Outputstream.
 *
 * @param stream - the java OutputStream you wish to write to
 * @exception IOException if anything can't be written.
 */
public void write(OutputStream stream) throws IOException {
    for (SXSSFSheet sheet : _xFromSxHash.values()) {
        sheet.flushRows();
    }

    //Save the template
    File tmplFile = File.createTempFile("poi-sxssf-template", ".xlsx");
    tmplFile.deleteOnExit();
    FileOutputStream os = new FileOutputStream(tmplFile);
    _wb.write(os);
    os.close();

    //Substitute the template entries with the generated sheet data files
    injectData(tmplFile, stream);
    tmplFile.delete();
}

首先,Apache-POI 是开源的,这意味着您可以根据需要自由修改它。在这种情况下,修改 write 方法比尝试通过扰乱全局临时目录来使其表现不同更好。

但这引出了一个问题:你为什么要这样做?查看 write 的代码,很明显该方法被设计为在自身之后进行清理。如果write正常终止,则在该方法返回之前临时文件将被删除。如果异常终止,则应在 JVM 退出时清理该文件。

尽管如此,如果临时文件仍然“泄漏”,那么编写一个定期查找并删除它们的外部脚本应该是一件简单的事情。

关于java - 如何将 System.setProperty 的范围限制为仅设置它的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36244118/

相关文章:

java - 从 EURID(EPP 协议(protocol))提供的 *.xsd 生成模型时出现 JAXB SAXParseException

java - createTempFile 是线程安全的吗?

java - 如何停止 Tomcat/Java 包装我的输出

java - "PKIX path building failed"和 "unable to find valid certification path to requested target"

java - 限制 liferay 中的 portlet 访问

java - Jade 无法创建代理 MyAgent

java - hibernate hbm : automatic (unwanted) update found

java - 将 BigInteger 转换为 int 数组的更快方法是什么?

java - 从 Java 检测 Android 物理键盘上的 Shift + Enter

Java 8 函数和类