2014-11-01 86 views
0

我有一個用java編寫的服務器,它偵聽特定的端口號。我也有一個Objective-C客戶端連接到這個服務器並進行通信。溝通工作正常。現在,我必須從終端獲取objective-c客戶端的輸出並將其放入由java服務器創建的文件中。我如何去做這件事?普通的FileWriter函數似乎不起作用。以下是我擁有的服務器的一部分。將客戶機的控制檯輸出寫入服務器中的文件

// Get the client message 
while((inputLine = bufferedReader.readLine()) != null) { 
    System.out.println(inputLine); 
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 

    //read a line from the console 
    String lineFromInput = in.readLine(); 
    File file = new File("./user_statistics.txt"); 
    if(!file.exists()){ 
     file.createNewFile(); 
    } 

    //create an print writer for writing to a file 
    fileWriter = new FileWriter(file); 
    //output to the file a line 
    fileWriter.write(lineFromInput); 
} 

//close the file 
fileWriter.close(); 
serverSocket.close(); 
+0

這是行不通的?你有沒有收到任何錯誤信息?它創建一個空文件還是什麼? – 2014-11-01 01:42:02

+0

它創建一個空文件...它不會寫入任何文件 – vasupradha 2014-11-01 01:46:10

回答

0

可以通過從客戶端(到目前爲止好)讀一本線開始,但你從控制檯獲取輸入,並嘗試寫的文件,而不是。您應該刪除控制檯的東西,從inputLine,而不是閱讀:

// Get the client message 
while((inputLine = bufferedReader.readLine()) != null) { 
    System.out.println(inputLine); 

    //read a line from the console 
    File file = new File("./user_statistics.txt"); 
    if(!file.exists()){ 
     file.createNewFile(); 
    } 

    //create an print writer for writing to a file 
    fileWriter = new FileWriter(file); 
    //output to the file a line 
    fileWriter.write(inputLine); 
} 

//close the file 
fileWriter.close(); 
serverSocket.close(); 

順便說一句:如果你關心性能,你應該使用的bufferedReader.read(char[] cbuf, int off, int len)方法,而不是.readLine()。你做了它的方式,將時間浪費在:

  • 檢查下一個行結局;
  • 創建String對象(並最終刪除它們);
  • 可能檢查是否需要更改字符編碼,具體取決於您的字符編碼設置;
  • 使用緩衝區遠低於最佳大小(我認爲幾KB是常態)。
+0

哇!太棒了......這個效果非常好......我不知道這個錯誤是什麼,我正在撓頭。謝謝!!!!!!它現在就像一種魅力! – vasupradha 2014-11-01 02:36:57

相關問題