BufferedWriter only works for the first time

I have a simple server-client program that takes information from a client and transfers it to the server. Messages are transmitted through the DatagramSocket. Then the server takes the message and writes it to a text file.

My initial message is working fine (printed to a file). However, if I start the client again, the new message will not be written to the file. I need to restart the server so that the message is printed again.

I have an arrayCopy method that copies two arrays and puts them in a larger array.

CLIENT

public static void main(String[] args) throws IOException { System.out.println("Enter Username"); BufferedReader usernameInput = new BufferedReader(new InputStreamReader(System.in)); // Get the Username String username = directoryInput.readLine(); byte[] usrname = username.getBytes(); //Copy Username to Array byte[] tempArray = copyarray(packetheader, usrname); buffer = tempArray; mypacket = new DatagramPacket(buffer, buffer.length, IPaddr, 40000); clientSocket = new DatagramSocket(); clientSocket.send(mypacket); 

Server

 public static void main(String args[]) throws Exception { String Database; textfile = "C:\\textfile.txt"; DatagramSocket serverSock = new DatagramSocket(40000); byte[] rbuf = new byte[97]; DatagramPacket recievedPacket = new DatagramPacket(rbuf, rbuf.length); serverSock.receive(recievedPacket); String byteToString = new String(recievedPacket.getData(), 0, recievedPacket.getLength(), "US- ASCII"); FileWriter fstream = new FileWriter(textfile); BufferedWriter out = new BufferedWriter(fstream); out.write(byteToString); out.close } 
+1
source share
1 answer

The following should do what you need, what you need is a loop that allows you to read the next package, the next, etc.

 public static void main(String args[]) throws Exception { String textfile = "C:\\textfile.txt"; DatagramSocket serverSock = new DatagramSocket(40000); byte[] rbuf = new byte[97]; DatagramPacket recievedPacket = new DatagramPacket(rbuf, rbuf.length); while(true) { serverSock.receive(recievedPacket); String byteToString = new String(recievedPacket.getData(), 0, recievedPacket.getLength(), "US-ASCII"); FileWriter fstream = new FileWriter(textfile); BufferedWriter out = new BufferedWriter(fstream); out.write(byteToString); out.close(); recievedPacket.setLength(rbuf.length); } } 

However, this will overwrite the file with a new message, rather than adding it (if that is what you wanted). If you want to save all messages, you probably want to move the file creation out of the loop.

0
source

All Articles