2014-02-14 44 views
1

我寫了一個Runnable類Java的可運行文件IO

private static class Processing implements Runnable { 
    private static File file; 
    private static byte[] message; 
    public Processing (File f, byte[] m){ 
     this.file = f; 
     this.message = m; 
    }  
    public void run(){ 
     WriteToFile(file , message); 
          ... other processing.... 
    } 

private static void WriteToFile(File f , byte[] msg){ 
    FileOutputStream fs = null; 
    try { 
     fs = new FileOutputStream(f) ; 
     fs.write( msg); 
     fs.flush(); 
     fs.close(); 
    }catch (Exception e){ 
     e.printStackTrace(); 
    } 

} 

在主類

public class MainClass{ 
    public void somemethod(){ 
     .... 
     (new Thread(new Processing (<somefile> , <somebytes>))).start(); 
     .... 
    } 

} 

我的問題是

  1. 是這個方法正確嗎?我的願望是提高文件io(在 WriteToFile方法),因爲MainClass被超過1000個 用戶調用。
  2. 如何在代碼中模擬1000個用戶?是

    for (int i = 0 ; i<1000 ...){ 
        (new Thread(new Processing (<somefile> , <somebytes>))).start(); 
    } 
    

感謝

回答

3
  • 對於Q1:看起來不錯,但請記住,你總是在finally塊關閉流,因爲寫入操作可能會失敗,這可能會使您文件句柄搖晃。

  • 對於Q2:只要你沒有寫入1000個線程的同一個文件,那麼你就需要考慮線程的安全性。

3

我同意Neeveks的回答,但我可以看到兩個額外的問題。

1)filemessage應該是實例變量,不應該是靜態的。將它們設置爲靜態意味着您一次只能管理一個文件和一條消息。

2)方法的名稱以Java中的小寫字母開頭。請將WriteToFile重命名爲writeToFile。這不是一個編程問題,但它有助於閱讀你的代碼。

1

看起來不錯,你可以嘗試內存映射文件,如果數據很大。您可以從已有的關於寫入文件here的答案中獲得一些參考。