I have a problem with writing incoming information from a client to this program. The data comes in and there is output every second from the System.out, but the FileWriter only prints the first line of output from when the program was started. I stop the program manually, and check the file after. I'm unsure of what's wrong, please help.
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.net.*;
import java.io.*;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Server {
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
String msg_received;
FileWriter fw = new FileWriter("HeartData.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
System.out.println("Waiting for Android client to connect...");
while (true)
{
try
{
ServerSocket server = new ServerSocket(2323);
Socket s = server.accept();
server.close();
InetAddress clientAddress = s.getInetAddress();
System.out.println("Incoming connection from: " + clientAddress.getHostName() + "[" + clientAddress.getHostAddress() + "]");
DataInputStream DIS = new DataInputStream(s.getInputStream());
msg_received = DIS.readUTF();
out.println(msg_received + "," + LocalTime.now() + "," + LocalDate.now());
System.out.printf("Android says: %sat %s%n", msg_received, LocalTime.now());
}
catch (IOException e){e.printStackTrace();}
finally {
out.close();
}
}
}
}
Example Output:
Waiting for Android client to connect...
Incoming connection from: hostname.domain[ipaddress] Android says: SOMETHING at 10:51:06.013
You have this structure:
while (true) {
try {
// Code which writes one line
} finallly {
out.close();
}
}
In other words, you're closing the output after the first line, but continuing to do work. That's not going to reopen the output...
You should really use a try-with-resource block for the whole thing, with the while loop entirely inside it, so that you don't close the writer until your whole loop has finished. (Admittedly at the moment it can only finish due to an exception... you might want to add some non-exceptional way of stopping the loop...)
See more on this question at Stackoverflow