I am coding a function which will check if file CQ.txt exists and if so, read from it. I have been having an issue where I have declared a printwriter
outside of the while loop. Later in the application, it is supposed to write Question 1: correct or Question 2: correct to the file.
But, it does not. It creates the text file but when I check it, it shows up as empty.
Here is the code, thank you in advance:
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");
}
}
}
}