Hi, I am trying to create a Client/Server application...when client is initialized it reads a file line by line and sends each line to the server which does some sort of action to the line (in my code it capitalizes the line) and writes it to a file. I have the client/server connection working fine and the reading is working fine. Currently when I run the client it sends all lines to the server, one by one, and the server prints each one to the screen capitalized...now the problem is when writing those lines (instead of printing them) to a file. I have read up on how to make it write to a file in Java and it works but its only printing the first or last line no matter how I shuffle the code around, any ideas how to fix it?

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

class UDP_Server {
	public static void main(String args[]) throws Exception
	{
		//create DatagramSocket
		DatagramSocket serverSocket = new DatagramSocket(9876);
		
		//create byte array to contain msgs received from client and to send to client
		byte[] receiveData = new byte[1024];
		byte[] sendData = new byte[1024];
		
		FileWriter fwriter = new FileWriter("file.txt");
		BufferedWriter writer = new BufferedWriter(fwriter);
		
		while(true) {			
			//create and receive packet from client
			DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
			serverSocket.receive(receivePacket);
			
			//get data from packet received from client
			String sentence = new String(receivePacket.getData());
			
			//get IP address and port number
			InetAddress IPAddress = receivePacket.getAddress();
			int port = receivePacket.getPort();
			
			//capitalize the packet msg received from client
			String capitalizedSentence = sentence.toUpperCase();
						
			writer.write(capitalizedSentence);
			writer.newLine();
			writer.close();
			
			//send the new capitalized msg into a packet to the client
			sendData = capitalizedSentence.getBytes();
			DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
			serverSocket.send(sendPacket);
		}
		
	}
}

I think it might have to do with the position of the close() but even if I changed it around I couldn't get it to work. Thanks for any insight and sorry if its a newbie question :)

EDIT: that is just the server code and its using UDP.

Recommended Answers

All 3 Replies

The problem you are getting is one of appending to the file instead of replacing.
The way you have coded it right now, the writer replaces the file with the last incoming sentence, instead of appending to the file.

The trick is that there are 2 constructors for the FileWriter class.
You have the one with just the name of the file to make. However, there is a second one with 2 parameters: the name of the file, and a boolean to append or not.

Conclusion being: Change FileWriter fwriter = new FileWriter("file.txt"); to

FileWriter fwriter = new FileWriter("file.txt",true);

The problem you are getting is one of appending to the file instead of replacing.
The way you have coded it right now, the writer replaces the file with the last incoming sentence, instead of appending to the file.

The trick is that there are 2 constructors for the FileWriter class.
You have the one with just the name of the file to make. However, there is a second one with 2 parameters: the name of the file, and a boolean to append or not.

Conclusion being: Change FileWriter fwriter = new FileWriter("file.txt"); to

FileWriter fwriter = new FileWriter("file.txt",true);

I think that would solve my issue of appending all sentences but now I have another issue related to the .close() statement, this will close the BufferedWriter but at the position I have it, it closes the BufferedWriter after the first sentence is written to the txt file. Since this loop is only exited on the Command Prompt if I put the .close() outside the loop, it is unreachable (error). Where would be the best place to put the .close()? Or is there a better way to do the UDP server that I should look into?

In your current situation, you close the stream after the first sentence, and the next time you start the while(true) loop, you are trying to use the writer you just closed, thus resulting in an error.

Embed your while(true) loop in a try/finally structure, and put the close() in the 'finally' statement. When you exit the program, the 'finally' part will make sure your streams are closed.

If you want to stop writing after a specified number of sentences, you could change the while(true) loop with a for-loop, choosing how many times the loop is run.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.