2016-04-21 106 views
0

我正在編寫一個函數,它將檢查文件CQ.txt是否存在,如果是,請從中讀取。我一直有一個問題,我已經在while循環之外聲明瞭printwriter。在應用程序的後面,應該寫出問題1:正確或問題2:對文件更正。寫入文本文件問題Java

但是,它沒有。它創建文本文件,但是當我檢查它時,它顯示爲空。

下面是代碼,預先感謝您:

package receiverhost; 

import java.io.*; 
import java.net.*; 

public class ReceiverHost { 
public static void main(String[] args) throws Exception { 

    //set up socket on port 5000 
    ServerSocket Server = new ServerSocket(5000); 

    //set up "cookie"/ text file to be written to/ read from eventually 
    Writer DB = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("CQ.txt"), "utf-8")); 

    System.out.println("TCPServer Waiting for client on port 5000"); 

    while(true){ 

     //declare string fromclient 
     String fromclient; 
     Socket connected = Server.accept(); 
     System.out.println(" The client" + " " + connected.getInetAddress() + ":" + connected.getPort() + " is connected "); 

     //read/ retrieve client output stream 
     BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connected.getInputStream())); 

      fromclient = inFromClient.readLine(); 
      if(fromclient.equals("Q1C")){ 
       //write to CQ.txt 
       DB.write("Q1: correct"); 
      } 

      if(fromclient.equals("Q2C")){ 
       //write to CQ.txt 
       DB.write("Q2: correct"); 
      } 
     } 
    } 
} 
+0

您是否試過在簡單的HelloWorld程序中寫入文件? – DavidS

+0

@DavidS我做的第一件事,它顯然是xD .. –

回答

0

的BufferedWriter顧名思義緩衝到文件的寫入。任何對BufferedWriter的寫入都將寫入內存緩衝區而不是直接寫入文件。

這樣做是出於提高效率的目的,併爲了節省CPU浪費的IO時間。

每次調用bufferedWriter.write其附加的數據到緩衝器,寫緩衝器中的數據到文件僅當緩衝區croses閾值時,默認或通過的BufferedWriter供給(FileWriter的,緩衝區大小)構造時間。

建議刷新寫入程序並在將所有數據寫入bufferedWriter後將其關閉。

理想的樣本代碼看起來像

Writer DB = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("CQ.txt"), "utf-8")); 

DB.write("Dummy Data1 "); 
DB.write("Dummy Data2"); 

DB.flush(); 
DB.close(); 
收盤後

並刷新你應該能夠看到文件中的所有數據。