2011-07-21 99 views
0

您能否建議如何處理這些情況?我知道在第二個例子中,unix會發生這種情況非常罕見,是嗎?如果訪問權限沒有問題。此外,該文件甚至不會被創建。我不明白爲什麼IOException會出現,無論它是否被創建,爲什麼我們不得不打擾IOException呢?如何處理已創建但發生IOException的損壞文件?

但在第一個例子中,會有一個損壞的殭屍文件。現在,如果你告訴用戶再次上傳,同樣的事情可能會發生。如果你不能這樣做,並且輸入流沒有標記。你丟失了你的數據?我真的不喜歡如何在Java中做,我希望新的IO在Java 7中更好

是它通常將其刪除

public void inputStreamToFile(InputStream in, File file) throws SystemException { 

    OutputStream out; 
    try { 
     out = new FileOutputStream(file); 
    } catch (FileNotFoundException e) { 
     throw new SystemException("Temporary file created : " + file.getAbsolutePath() + " but not found to be populated", e); 
    } 

    boolean fileCorrupted = false; 
    int read = 0; 
    byte[] bytes = new byte[1024]; 

    try { 
     while ((read = in.read(bytes)) != -1) { 
      out.write(bytes, 0, read); 
     } 
    } catch (IOException e) { 
     fileCorrupted = true; 
     logger.fatal("IO went wrong for file : " + file.getAbsolutePath(), e); 
    } finally { 
     IOUtils.closeQuietly(in); 
     IOUtils.closeQuietly(out); 

        if(fileCorrupted) { 
     ??? 
        } 
    } 
} 


public File createTempFile(String fileId, String ext, String root) throws SystemException { 

    String fileName = fileId + "." + ext; 

    File dir = new File(root); 

    if (!dir.exists()) { 
     if (!dir.mkdirs()) 
      throw new SystemException("Directory " + dir.getAbsolutePath() + " already exists most probably"); 
    } 

    File file = new File(dir, fileName); 

    boolean fileCreated = false; 
    boolean fileCorrupted = false; 
    try { 
     fileCreated = file.createNewFile(); 
    } catch (IOException e) { 
     fileCorrupted = true; 
     logger.error("Temp file " + file.getAbsolutePath() + " creation fail", e); 
    } finally { 

     if (fileCreated) 
      return file; 
     else if (!fileCreated && !fileCorrupted) 
      throw new SystemException("File " + file.getAbsolutePath() + " already exists most probably"); 
     else if (!fileCreated && fileCorrupted) { 

     } 
    } 

} 

回答

1

我真的不喜歡這如何在Java中完成的,我希望新的IO在Java 7中更好

我不知道Java是怎麼一比的方式任何其他編程語言/環境不同,你正在使用它:

  • 一個客戶端通過
  • 當你讀它,你把它寫入到本地文件

不管語言/工具/環境的電線一些數據發送給你的,它是可能的連接是中斷或丟失,導致客戶走開,磁盤死亡或發生任何其他錯誤。任何和所有環境都可能發生I/O錯誤。

在這種情況下你能做什麼高度依賴於情況和發生的錯誤。例如,數據是以某種方式構建的,例如,您可以要求用戶從記錄1000恢復上傳?但是,這裏沒有一個適合所有人的解決方案。

+0

我明白,在網絡堆棧中可能會出現問題。但我主要將流處理爲本地套接字或緩衝流,並且因爲它具有所有相同的接口,所以它會拋出IOException異常,並且開發人員不知道他是否處理了設備上沒有剩餘空間或者確切地說是什麼。例如創建文件時IOException不應該不存在。它可以創建它,也可以不創建,或者開發人員應該知道發生了什麼,但是我找不到在這種情況下發生IOException的原因...... – lisak

+0

異常告訴我什麼是錯誤很好。但大多數情況下,開發人員都知道可能出現的問題,並可以在catch塊中對其進行反應。 – lisak

+0

@lisak - 開發人員如何意識到任何問題?要麼從每個操作返回一個狀態代碼,要麼拋出異常,要麼需要第二個顯式操作來驗證第一個操作。我看到過多的C代碼,開發人員沒有檢查操作的返回代碼。至於第二個明確的操作......如果開發人員不能檢查返回代碼,他/她會做第二次操作的可能性不大。檢查異常迫使你意識到發生了什麼。 – parsifal