[英]How can I limit the scope of System.setProperty to only to the method that sets it?
我正在進行導出,要求將文件存儲在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")
更改時都向其添加新路徑。 我無法更改臨時文件的創建方式,因為它不是由我執行,而是由SXSSFWorkbook.java
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)
,並使用(例如)線程createTempFile(String prefix, String suffix, File directory)
跟蹤“當前”臨時目錄。
更好的是,使用java.nio.Files
的等效方法。
不幸的是,我無法進行上述更改,因為
createTempDirectory
是由我無法更改的另一種方法完成的(SXSSFWorkbook
為我完成了此操作)。
因此,我看了一下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.io.tmpdir”的第一個值保存在臨時變量中,並在完成后將其設置回去嗎?
String defaultDir = System.getProperty("java.io.tmpdir")
System.setProperty("java.io.tmpdir", System.getProperty("java.io.tmpdir")+pathSpecificToFirstExport);
//createTempFile method
System.setProperty("java.io.tmpdir",defaultDir);
你不能 setProperty
始終是全局的。 相反,您應該做的是
Files.createTempDirectory(System.getProperty("java.io.tempdir") + pathSpecificToFirstExport);
如果可以通過maven命令運行作業,則可以嘗試
mvn <command to execute job> -Djava.io.tmpdir=absolutePathSpecificToFirstExport
並為每個作業運行一個mvn命令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.