我正在編寫一個函數,它將檢查文件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");
}
}
}
}
您是否試過在簡單的HelloWorld程序中寫入文件? – DavidS
@DavidS我做的第一件事,它顯然是xD .. –