我在将来自客户端的传入信息写入此程序时遇到问题。数据进入并且System.out每秒都有输出,但FileWriter只打印程序启动时的第一行输出。我手动停止程序,然后检查文件。我不确定什么是错的,请帮忙。
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();
}
}
}
}
示例输出:
等待Android客户端连接...
来自:hostname.domain [ipaddress]的传入连接 Android说:SOMETHING 在10:51:06.013
的
答案 0 :(得分:3)
你有这个结构:
while (true) {
try {
// Code which writes one line
} finallly {
out.close();
}
}
换句话说,您在第一行之后关闭输出,但继续工作。这不会重新打开输出......
你应该真的使用try-with-resource块来完成整个事情,while循环完全在里面,这样你就不会关闭编写器,直到整个循环都有完了。 (不可否认,目前它只能因异常而完成......你可能想添加一些阻止循环的非常规方法......)