修改后的代码如下:

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

public class ChatSimple {
   public static void main(String[] args) {
      try {
         Socket s = new Socket(args[0], 8080);
         System.out.println("Connected");
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
         PrintWriter out = new PrintWriter(s.getOutputStream(), true);
         
         // 读取之前的聊天记录
         File file = new File("Temp.txt");
         if (file.exists()) {
            BufferedReader recordIn = new BufferedReader(new FileReader(file));
            String line;
            while ((line = recordIn.readLine()) != null) {
               System.out.println(line);
            }
            recordIn.close();
         }
         
         String line;
         while ((line = br.readLine()) != null) {
            out.println(line);
            if (line.equals("bye")) break;
            System.out.println("Server response: " + in.readLine());
            
            // 写入聊天记录
            BufferedWriter recordOut = new BufferedWriter(new FileWriter(file, true));
            recordOut.write(line);
            recordOut.newLine();
            recordOut.flush();
            recordOut.close();
         }
         
         s.close();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

修改的部分主要在读取和写入聊天记录的部分。我们在代码中加入了读取之前的聊天记录的部分,如果之前有聊天记录,则将其输出到控制台。同时,每次发送消息后,将其写入本地的Temp.txt文件中。

运行程序后,输入对方的IP地址,即可进行聊天。聊天记录将会被保存在本地的Temp.txt文件中。每次运行程序时,Temp.txt文件中的聊天记录会被恢复

认真阅读ChatSimple代码在上述代码基础上进行修改使用第22章文件和流章的使用流节的知识将ChatSimple工程中的聊天记录写入本地的Temptxt查看是否成功。每次使用程序时请恢复以前的聊天记录。需在同一局域网输入对方IP

原文地址: https://www.cveoy.top/t/topic/fbE0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录