LongerSking 发表于 2022-9-26 15:16:36

Java如何反序列出(读取文本中所有内容)

主类
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class StudentSystem implements Serializable{
    staticArrayList<User> Ulist = new ArrayList<>();
    static ArrayList<Student> Slist = new ArrayList<>();
    staticUser user = new User();
    staticStudent student = new Student();
    static String path1,path2;
    static {
      path2 = "studentsystem\\student.txt";
      path1 = "studentsystem\\user.txt";
    }
//    static File file1 = new File(path1),file2 = new File(path2);
//    static {
//      if (!file1.exists()) {
//            try {
//                file1.createNewFile();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            if (!file1.exists()) {
//                try {
//                  file1.createNewFile();
//                } catch (IOException e) {
//                  e.printStackTrace();
//                }
//            }
//      }
//    }
    public static void main(String[] args) throws Exception {
      readFile(Ulist,null,path1,user,null);
      enterUserSystem(Ulist);
    }

    private static void enterUserSystem(ArrayList<User> list) throws Exception{
      User user = new User();
      System.out.println("---------------欢迎来到Java版学生管理系统---------------");
      while (true){
            System.out.println("--------请选择1.登录 2.注册 3.忘记密码--------");
            Scanner sc = new Scanner(System.in);
            String choice = sc.next();
            switch (choice) {
                case "1":
                  logIn(Ulist);
                  break;
                case "2":
                  register(Ulist);
                  writeFile(Ulist,path1);
                  break;
                case "3":
                  forgotPassword(Ulist);
                  break;
                case "4":
                  System.out.println("---------------退出用户界面---------------");
                  System.exit(0);
                default:
                  System.out.println("选项不存在!默认退出");
                  System.exit(0);
            }
      }
    }



    private static void enterStudentSystem() throws Exception {
      loop: while(true){
            System.out.println("添加学生信息,请按1");
            System.out.println("删除学生信息,请按2");
            System.out.println("修改学生信息,请按3");
            System.out.println("查询学生信息,请按4");
            System.out.println("退出,请按5");
            System.out.print("请输入您的选择:");
            Scanner sc = new Scanner(System.in);
            String choice = sc.next();
            switch (choice) {
                case "1":
                  readFile(null,Slist,path2,null,student);
                  addStudent(Slist);
                  writeFile(Slist,path2);
                  break;
                case "2":
                  readFile(null,Slist,path2,null,student);
                  deleteStudent(Slist);
                  break ;
                case "3":
                  readFile(null,Slist,path2,null,student);
                  changeStudent(Slist);
                  writeFile(Slist,path2);
                  break ;
                case "4":
                  readFile(null,Slist,path2,null,student);
                  queryStudent(Slist);
                  break ;
                case "5":
                  System.out.println("---------------退出学生管理系统---------------");
                  break loop;
                default:
                  System.out.println("选项不存在!请重新输入");
            }
      }
    }
    private static void register(ArrayList<User> list) throws IOException {
      String s1,s2,s3,s4;
      s1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXVZ";
      s3 = "0123456789xX";
      s2 = "0123456789";
      s4 = "~`!@#$%^&*()_+-={}[]|\\;:'\"<>,.?/";
      User user = new User();
      Scanner sc = new Scanner(System.in);
      String userName,password,repassword,personId,phoneNum;
      boolean flag1 = true,flag2 = true,flag3 = true,flag4 = true;
       while(flag3) {
         System.out.print("请输入用户名(长度必须在3到15位):");
         userName = sc.next();
         int l = userName.length();
            if(l < 3||l > 15){
                System.out.println("输入用户名语法错误,请重新输入");
            }
         if(userContain(list,userName)) {
               System.out.println("用户名已被注册,请再输入其他用户名!");
               continue;
         }else{
               System.out.println("注册用户名成功");
               user.setUserName(userName);
               flag3 = false;
         }
      }
      while(flag4){
            System.out.print("请设置密码(长度必须在8到15位):");
            password = sc.next();
            int l = password.length();
            if(l < 8||l > 15){
                System.out.println("设置密码语法错误,请重新输入");
            }else {
                System.out.print("密码设置成功,请再次输入核对:");
               while (flag4){
                   repassword = sc.next();
                   if(password.equals(repassword)){
                     System.out.println("密码核对成功,已录入");
                     repassword = null;
                     user.setPassword(password);
                     flag4 = false;
                   }else {
                     System.out.println("密码核对错误,请再次核对");
               }
                }
            }
      }
      while (flag2){
            System.out.println("请输入身份证号码:");
            personId = sc.next();
            String id = personId;
            if((id.charAt(0)=='0')||(id.length()!=18)){
                flag2 = true;
            }else if (isContain(id.substring(0,17).toString(),s1)){
                flag2 = true;
            }else if(!(isContain(id.substring(17),s3))){
                flag2 = true;
            }else {
                flag2 = false;
            }
            if(flag2 == false){
                user.setPersonId(id);
            }else {
                System.out.println("输入错误,请重新输入:");
            }
      }
      while (flag1 ){
            System.out.println("请输入手机号码:");
            phoneNum = sc.next();
            if((isContain(phoneNum,s1))||(isContain(phoneNum,s4))){
                flag1 = true;
            }else if((phoneNum.length() != 11)||phoneNum.charAt(0) == '0'){
                flag1 = true;
            }else {
                flag1 = false;
            }
            if(flag1 == true){
                System.out.println("输入格式错误!请重新输入:");
            }else {
                System.out.println("输入成功");
                user.setPhoneNum(phoneNum);
            }
      }
      if((flag2 == flag3 == flag1 == flag4)&&(flag2 == false)){
         System.out.println("注册成功");
            list.add(user);
      }else {
            System.out.println("注册失败");
      }
    }
    private static void logIn(ArrayList<User> list) throws Exception {
      Scanner sc = new Scanner(System.in);
      System.out.print("请输入用户名:");
      String name = sc.next();
      while (true){
            if(userContain(list,name)){
                break ;
            }else {
                System.out.println("未找到该用户,请先注册");
                return;
            }
      }
      System.out.print("请输入密码:");
      String key = sc.next();
       while (true){
         String code = getCode();
         System.out.println("验证码:" + code);
         System.out.print("请输入验证码:");
         String recode = sc.next();
         if(code.equalsIgnoreCase(recode)){
               System.out.println("验证码正确");
               break;
         }else{
               System.out.println("验证码输入错误,请重新输入");
         }
       }
      User user = new User(name,key,null,null);
      if(isRight(list,user)){
            System.out.println("登录成功,正在进入学生管理系统");
            enterStudentSystem();
      }else{
            System.out.println("登录失败,账户名或密码输入错误");
      }
    }
    private static void forgotPassword(ArrayList<User> list){
      Scanner sc = new Scanner(System.in);
      System.out.print("请输入用户名:");
      String name = sc.next();
      while (true){
            if(userContain(list,name)){
                break ;
            }else {
                System.out.println(userContain(list, name));
                System.out.println("未找到该用户,请先注册");
                return;
            }
      }
      int index = userByName(list,name);
      User user = new User();
      user = list.get(index);
      String pI, pN, key, rekey;
       while (true){
         System.out.print("请输入身份证号码:");
         pI = sc.next();
         System.out.print("请输入电话号码:");
         pN = sc.next();
         if (!(user.getPersonId().equalsIgnoreCase(pI) && user.getPhoneNum().equals(pN))) {
               System.out.println("身份证或电话号码输入错误!!!");
               continue;
         }else {
               break;
         }
       }
      clock: while(true){
            System.out.print("请设置密码(长度必须在8到15位):");
            key = sc.next();
            int l = key.length();
            if(l < 8||l > 15){
                System.out.println("设置密码语法错误,请重新输入");
            }else {
                System.out.print("密码设置成功,请再次输入核对:");
                while (true){
                  rekey = sc.next();
                  if(key.equals(rekey)){
                        System.out.println("密码核对成功,已录入");
                        rekey = null;
                        break clock;
                  }else {
                        System.out.println("密码核对错误,请再次核对");
                        continue ;
                  }
                }
            }
      }
       user.setPassword(key);
    }
    private static int userByName(ArrayList<User> list,String name) {
      for (int i = 0; i < list.size(); i++) {
            User user = new User();
            user = list.get(i);
            if(user.getUserName().equals(name)){
                return i;
            }
      }
      return -1;
    }
    public static void addStudent(ArrayList<Student> list) throws IOException {
      Student stu = new Student();
      Scanner sc = new Scanner(System.in);
      String id = null;
      while (true) {
            System.out.print("请输入学号:");
            id = sc.next();
            boolean key = idOnly(list, id);
            if(key){
                System.out.println("您添加的学号已存在,请重新输入!!!");
            }else{
                stu.setId(id);
                list.add(stu);
                break;
            }
      }
      System.out.print("请输入姓名:");
      String name = sc.next();
      System.out.print("请输入籍贯:");
      String address = sc.next();
      System.out.print("请输入年龄:");
      int age = sc.nextInt();
         stu = new Student(name,id,address,age);
      list.add(stu);
      System.out.println("学生信息添加成功!");
    }
    public static void deleteStudent(ArrayList<Student> list){
      Scanner sc = new Scanner(System.in);
      System.out.print("请输入您的学号来删除对应信息:");
      String id = sc.next();
      int bool = getIndex(list,id);
      if(bool >= 0){
            list.remove(bool);
            System.out.println("删除成功");
      }else{
            System.out.println("很抱歉,未能找到您的学号!");
      }
    }
    public static void changeStudent(ArrayList<Student> list){
            System.out.print("请输入您的学号以便于修改您对应的信息:");
            Scanner sc = new Scanner(System.in);
            String id = null;
            while (true) {
               id = sc.next();
                boolean flag = idOnly(list, id);
                if(flag){
                  break;
                }else{
                  System.out.println("您输入的学号不存在!请重新输入!");
                }
            }
            int index = getIndex(list,id);
          First: while(true) {
                  System.out.println("修改学号请按1\n修改姓名请按2\n修改年龄请按3\n修改籍贯请按4\n其余均为放弃修改\n");
                  System.out.print("请按照提示输入:");
                  String choice = sc.next();
                  switch (choice) {
                        case "1":
                            System.out.print("请输入您想修改学号为:");
                            list.get(index).setId(sc.next());
                            break;
                        case "2":
                            System.out.print("请输入您想修改姓名为:");
                            list.get(index).setName(sc.next());
                            break;
                        case "3":
                            System.out.print("请输入您想修改年龄为:");
                            list.get(index).setAge(sc.nextInt());
                            break;
                        case "4":
                            System.out.print("请输入您想修改籍贯为:");
                            list.get(index).setAddress(sc.next());
                            break;
                        default:
                            System.out.println("退出");
                  }
                  Second:while(true) {
                      System.out.println("是否继续修改?(yes/no)");
                      String chance = sc.next();
                      if (chance.equalsIgnoreCase("no")) {
                        break First;
                      } else if (chance.equalsIgnoreCase("yes")) {
                        System.out.println("继续修改");
                        break Second;
                      } else {
                        System.out.println("输入错误请重新选择:");
                      }
            }
            }
    }
    public static void queryStudent(ArrayList<Student> list){
      if(list.size() == 0){
            System.out.println("没有学生信息,请添加后再查询");
            return;
      }
      System.out.println("学号\t\t\t" + "姓名\t" + "年龄\t" + "籍贯");
      for (int i = 0; i < list.size(); i++) {
            Student stu = new Student();
            stu = list.get(i);
            System.out.println(stu.getId()+"\t"+stu.getName()+"\t"+stu.getAge()+"\t"+stu.getAddress());
      }
    }
    public static boolean idOnly(ArrayList<Student> list,String id) {
       int flag = getIndex(list,id);
       if(flag >= 0){
         return true;
       }
       return false;
    }
    public static int getIndex(ArrayList<Student> list,String id){
      for (int i = 0; i < list.size(); i++) {
            String sid = list.get(i).getId();
            if (sid.equals(id)) {
                return i;
            }
      }
      return -1;
    }
    public static boolean isContain(String s1,String s2){
      for (int i = 0; i < s1.length(); i++) {
            char c1 = s1.charAt(i);
            for (int k = 0; k < s2.length(); k++) {
                char c2 = s2.charAt(k);
                if(c2 == c1){
                  return true;
                }
            }
      }
      return false;
      }
    public static boolean userContain(ArrayList<User> list,String name){
      for (int l = 0; l < list.size(); l++) {
            User user = new User();
            user = list.get(l);
            String rightName = user.getUserName();
            if (rightName.equals(name)){
                return true;
            }
      }
      return false;
    }
    private static boolean isRight(ArrayList<User> list,User user) {
      String n = user.getUserName();
      String p = user.getPassword();
      for (int i = 0; i < list.size(); i++) {
         User reuser = new User();
         reuser = list.get(i);
            if((reuser.getPassword().equals(p))&&(reuser.getUserName().equals(n))){
               return true;
         }
      }
      return false;
    }
    public static String getCode(){
      ArrayList<Character> clist = new ArrayList<>();
      for (int i = 0; i < 26; i++) {
            clist.add((char)('a'+i)) ;
            clist.add((char)('A'+i)) ;
      }
      StringBuilder sb = new StringBuilder();
      Random random = new Random();
      for (int l = 0; l < 4; l++) {
            int index = random.nextInt(clist.size());
            char c = clist.get(index);
            sb.append(c);
      }
      int num = random.nextInt(10);
      sb.append(num);
      char[] chars = sb.toString().toCharArray();
      for (int i = 0; i < chars.length; i++) {
            int n = random.nextInt(chars.length);
            char temp = chars;
             chars = chars;
             chars = temp;
      }
      return new String(chars);
    }
    public static void writeFile(ArrayList<?> list,String path) throws Exception{
      int length = list.size();
      ObjectOutputStream oos = null;
      OutputStream ops = null;
      for (int i = 0; i < length; i++) {
            ops = new FileOutputStream(path,true);
            oos = new ObjectOutputStream(ops);
            oos.writeObject(list.get(i));
            oos.writeObject('\n');
      }
      oos.flush();
      oos.close();
      ops.close();
    }
    public static void readFile(ArrayList<User> list1,ArrayList<Student> list2,String path,User user,Student student) throws Exception {
      InputStream inputStream;
      ObjectInputStream ois = null;

      //String str;
      try {
            if(student == null) {
                  inputStream = new FileInputStream(path);
                   /* int len;
                  byte[] b = new byte;
                  while((len = inputStream.read(b)) != -1){
                         str = new String(b,0,len);
                  }*/
                  ois = new ObjectInputStream(inputStream);
                  user = (User) ois.readObject();

                list1.add(user);

            }
      } catch (Exception e) {
            e.printStackTrace();
         /* System.out.println("没有任何数据,请先添加用户数据");
            System.out.println("是否选择注册账户?(yes/no)");
            String choice;
            Scanner scanner = new Scanner(System.in);
            choice = scanner.next();
            if (choice.equalsIgnoreCase("yes")){
                register(Ulist);
                writeFile(Ulist,path1);
            }else {
                System.out.println("默认退出");
                System.exit(0);
            }*/
      }
      try {
            if(user == null){
                  inputStream = new FileInputStream(path);
                  ois = new ObjectInputStream(inputStream);
                  student= (Student) ois.readObject();
                  list2.add(student);
            }
      } catch (Exception e) {
            e.printStackTrace();
         /* System.out.println("没有任何数据,请先添加学生数据");
            System.out.println("是否选择添加学生信息?(yes/no)");
            String choice;
            Scanner scanner = new Scanner(System.in);
            choice = scanner.next();
            if (choice.equalsIgnoreCase("yes")){
                addStudent(Slist);
                writeFile(Ulist,path1);
            }else {
                System.out.println("默认退出");
                System.exit(0);
            }*/

      }
    }

}


用户类

import java.io.Serializable;

public class User implements Serializable {
    public String userName;
    private String password;
    private String personId;
    private String phoneNum;

    public User() {
    }

    public User(String userName, String password, String personId, String phoneNum) {
      this.userName = userName;
      this.password = password;
      this.personId = personId;
      this.phoneNum = phoneNum;
    }

    public String getUserName() {
      return userName;
    }

    public void setUserName(String userName) {
      this.userName = userName;
    }

    public String getPassword() {
      return password;
    }

    public void setPassword(String password) {
      this.password = password;
    }

    public String getPersonId() {
      return personId;
    }

    public void setPersonId(String personId) {
      this.personId = personId;
    }

    public String getPhoneNum() {
      return phoneNum;
    }

    public void setPhoneNum(String phoneNum) {
      this.phoneNum = phoneNum;
    }
}

学生类

import java.io.Serializable;

public class Student implements Serializable {
      privateString name;
      privateString id;
      privateString address;
      privateint age;

    public Student(String name, String id, String address, int age) {
      this.name = name;
      this.id = id;
      this.address = address;
      this.age = age;
    }

    public Student() {
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public String getId() {
      return id;
    }

    public void setId(String id) {
      this.id = id;
    }

    public String getAddress() {
      return address;
    }

    public void setAddress(String address) {
      this.address = address;
    }

    public int getAge() {
      return age;
    }

    public void setAge(int age) {
      this.age = age;
    }
}

这代码文件路径我稍微改了一下

q1577271837 发表于 2022-9-26 15:16:37

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Temp {
    public static void main(String[] args) {
      try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader("填写你的文本路径"));
            while(bufferedReader.readLine() != null){
                System.out.println(bufferedReader.readLine());
            }
      } catch (FileNotFoundException e) {
            e.printStackTrace();
      } catch (IOException e) {
            e.printStackTrace();
      }
    }
}

LongerSking 发表于 2022-9-26 15:17:31

等一下不知道为毛自动翻译了
页: [1]
查看完整版本: Java如何反序列出(读取文本中所有内容)