我正在进行导出,要求将文件存储在 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/