簡體   English   中英

Java SE 6中通過錯誤處理移動文件

[英]moving files with error handling in Java SE 6

我想使用Java SE 1.6將文件移到其他位置

因此,我有兩個文件:

File srcFile, dstFile;

當我想將文件srcFile移到dstFile的位置時:

boolean result = srcFile.renameTo(dstFile);

但是可能會發生一些錯誤,結果將是錯誤的。 在這種情況下,我想問用戶是否要重復此操作。 哪個是最好的方法? 我會在這里使用goto語句,但是Java沒有它。

目前,我正在以這種方式進行操作:

boolean retry = false;
do {
    if (!srcFile.renameTo(dstFile)) {
        // TODO: Error during file replacement
        Object[] retryOptions = { "Yes", "Retry" };
        replaceFileOption = JOptionPane.showOptionDialog(frame, "There was a error durring moving file" + srcFile.getPath() + ". Skip this file?", "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                    retryOptions, retryOptions[0]);
        if (replaceFileOption == 2) 
            retry = true;
    }
} while (retry);

還有另一種方法,將不使用while()循環嗎?

當您的目標是避免額外的變數時,請按照以下方式進行操作

while (!srcFile.renameTo(dstFile)) {
       Object[] retryOptions = { "Yes", "Retry" };
       if (2 != JOptionPane.showOptionDialog(frame, "There was a error durring moving file" + srcFile.getPath() + ". Skip this file?", "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                retryOptions, retryOptions[0])) break;
}

您可以將代碼放入方法中,並在重試的情況下再次遞歸調用該方法。

但是,最后,您需要循環一些操作方式,因此您必須以任何方式循環。

您可以避免使用某個關鍵字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM