0

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");
            }
        }
    }
}
The Roy
  • 2,178
  • 1
  • 17
  • 33
mmmeeeker
  • 138
  • 9

2 Answers2

0

You should call 'write' method on BufferedWriter, and later 'close' it. Here is an example:

How to Write text file Java

Community
  • 1
  • 1
Adrián
  • 419
  • 2
  • 17
0

BufferedWriter as the name suggests buffers the write to file. Any write to BufferedWriter will be written to in memory buffers not to the file directly.

this is done for efficiency purposes and in order to save CPU time wasted for IO .

Each time you invoke bufferedWriter.write it appends the data to buffer, writes the buffer data to file only if Buffer croses the threshold , either default or supplied by BufferedWriter(FileWriter,BufferSize) constructor .

It is recomended to flush the writer and close it after you have all the data written to bufferedWriter.

ideally a sample code would look like

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

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

DB.flush();
DB.close();

after close and flush you should be able to see all your data in the file.

Akash Yadav
  • 2,411
  • 20
  • 32