[英]What is the best, and cleanest way to close a file in Java inside a finally block
我寫了一個方法來關閉對文件的寫入。 但是,一位高級開發人員建議我關閉 finally 塊中的文件。
這是我的方法:
private static void writetoFiles(String error) {
try {
File file = new File("errorcode.txt");
if (!file.exists()) {
file.createNewFile();
} else {
FileWriter updateerrorcode = new FileWriter("errorcode.txt");
updateerrorcode.write(error);
updateerrorcode.close();
}
} catch (IOException e) {
}
}
我在 stackoverflow 中閱讀了很多答案,但對於像我這樣的簡單案例來說,所有答案似乎都太復雜了。 有什么建議我應該如何 go 關於這個?
最簡潔的方法是使用try-with-resources語句來完成,如下所示:
private static void writetoFiles(String error) throws IOException {
//...
try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
updateerrorcode.write(error);
}
//...
}
如果方法無法處理,請不要在方法中捕獲異常:
如果方法writetoFiles
不能處理異常,它應該拋出相同的,以便調用方法可以適當地處理它。
private static void writetoFiles(String error) {
try {
File file = new File("errorcode.txt");
if (!file.exists()) {
file.createNewFile();
} else {
try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
updateerrorcode.write(error);
}
}
} catch (IOException e) {
// TODO: Handle error condition
}
}
指出一個單獨的問題...我認為您的示例中的邏輯是錯誤的。 如果 output 文件不存在,您的代碼所做的就是創建該文件。 只有當文件已經存在時,它才會將error
文本寫入其中。 我希望你想在這兩種情況下寫文本。 如果這是真的,則根本不需要createNewFile
調用,因為FileWriter
class 將創建該文件(如果該文件尚不存在)。 所以我認為你真正想要的是:
private static void writetoFiles(String error) {
try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
updateerrorcode.write(error);
} catch (IOException e) {
// TODO: Handle error condition
}
}
這將導致編寫器在正常執行情況和錯誤拋出情況下都正確關閉。 我假設在您的實際代碼中,當它被捕獲時,您將對IOException
執行某些操作。 我不知道你想在那里做什么,所以我不會提出任何建議。
如果你想嚴格使用finally
塊,你可以這樣做:
FileWriter updateerrorcode = new FileWriter("errorcode.txt");
try {
updateerrorcode.write(error);
}
catch (IOException e) {
// TODO: Handle error condition
}
finally {
updateerrorcode.close();
}
在添加 try-with-resource 構造之前,這是您在 Java 的早期版本中擁有的唯一選項。 在第二種方法中,您可能希望從close()
中捕獲一個錯誤,但在我使用 Java 的所有 25 年以上經驗中,我不記得對文件失敗的close()
調用。 我想如果您的目標卷上的磁盤空間不足並且close()
無法刷新流的寫入緩沖區,您就會明白這一點。 這個問題是較新方法的一個明顯優勢...關閉文件失敗不會影響write()
調用引發的異常的拋出/捕獲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.