我在將來自客戶端的傳入信息寫入此程序時遇到問題。數據進入,每秒從System.out輸出,但FileWriter僅打印程序啓動時的第一行輸出。我手動停止程序,然後檢查文件。我不確定什麼是錯的,請幫助。FileWriter只寫入第一行(啓用了追加模式,Java)
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說:在10 SOMETHING :51:06.013
請花些時間更容易地設置你的代碼的格式。溝多個併發的空白行,並確保一切都縮進慣用。 –
感謝您的反饋,它現在有多可讀? –
不是真的 - 查看'System.out.println'與'while'循環的縮進情況,以及結尾附近的多個空白行,以及垂直對齊的其中一個應該縮進的近距離大括號。您的IDE應該能夠幫助您非常輕鬆地格式化代碼。 –