java if(response.equals("验证成功,完成登录")) { System.out.println(response); response="";//登录成功后向用户发送 new Thread(new ReadThread(in)).start(); sendStr = sc.next(); String a; while (sendStr != null) { out.println(sendStr); System.out.println(sendStr); a=sendStr; try {/// fileWriter.write("ip地址:"); fileWriter.write(ipAddress); fileWriter.write(" "); fileWriter.write("时间:"); fileWriter.write(" "); fileWriter.write(" "); fileWriter.write(a); fileWriter.close(); }catch (IOException e) {} sendStr = sc.next(); System.out.println(sendStr); } }改进这段代码让它可以多次向配置文件中输入字符串
时间: 2024-02-10 09:16:24 浏览: 69
可以将文件写入的操作封装成一个方法,每次发送消息时调用该方法写入配置文件。同时,需要将文件写入的操作放在一个 try-catch 块中,避免发生异常导致程序崩溃。
改进后的代码如下:
```
if(response.equals("验证成功,完成登录")) {
System.out.println(response);
response="";//登录成功后向用户发送
new Thread(new ReadThread(in)).start();
sendStr = sc.next();
while (sendStr != null) {
out.println(sendStr);
System.out.println(sendStr);
try {
writeToFile(ipAddress, sendStr);
} catch (IOException e) {
e.printStackTrace();
}
sendStr = sc.next();
System.out.println(sendStr);
}
}
// 写入文件的方法
private void writeToFile(String ipAddress, String message) throws IOException {
FileWriter fileWriter = new FileWriter("config.txt", true);
fileWriter.write("ip地址:" + ipAddress + " ");
fileWriter.write("时间:" + new Date() + " ");
fileWriter.write(message);
fileWriter.close();
}
```
阅读全文