gpt4 book ai didi

java - 通过反序列化代码更改数据

转载 作者:行者123 更新时间:2023-12-02 11:28:36 27 4
gpt4 key购买 nike

我只是想知道如何更改反序列化中的数据。我的程序需要:

询问用户是否要更改学生信息并将新数据存储在文本文件中。

这是我的代码:

import java.util.*;
import java.io.*;
import java.io.Serializable;

public class Deserialization{

public static void main(String [] args) {

Student st1 = null;
Student st2 = null;
Student st3 = null;
String opcion=null;
Scanner lol=new Scanner (System.in);

try {
FileInputStream fileIn = new FileInputStream("input.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
st1 = (Student) in.readObject();
st2 = (Student) in.readObject();
st3 = (Student) in.readObject();
do{ //HERE IS WHEREI WANT TO ASK MY USER AND REALIZE IT
System.out.println("Want to change?\n");
opcion=lol.next();
lol.nextLine();
}while(opcion.equals("y")||opcion.equals("Y"));
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
return;
}

System.out.println("Deserialized File...");
System.out.println("Student 1");
System.out.println("Name: " +st1.name);
System.out.println("ID: " +st1.id);
System.out.println("Average: " +st1.average);
System.out.println("Student 2");
System.out.println("Name: " +st2.name);
System.out.println("ID: " +st2.id);
System.out.println("Average: " +st2.average);
System.out.println("Student 3");
System.out.println("Name: " +st3.name);
System.out.println("ID: " +st3.id);
System.out.println("Average: " +st3.average);
}
}

化解部分

最佳答案

假设您有一个像这样的学生类(class) -

public class Student {
private String Name;
private int ID;
private int Average;
/**
* @return the name
*/
public String getName() {
return Name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
Name = name;
}
/**
* @return the iD
*/
public int getID() {
return ID;
}
/**
* @param iD the iD to set
*/
public void setID(int iD) {
ID = iD;
}
/**
* @return the average
*/
public int getAverage() {
return Average;
}
/**
* @param average the average to set
*/
public void setAverage(int average) {
Average = average;
}


}

反序列化后,您将从文件中读取一个对象,现在您想要修改 Student 对象。

 st1 = (Student) in.readObject();
st2 = (Student) in.readObject();
st3 = (Student) in.readObject();

这里有 st1、st2 和 st3 Student 对象。您可以通过调用Student对象的setter方法来修改st1名称。例如,如果您想修改学生姓名,您只需调用

st1.setName("modifyName");

修改后,您可以按照常规方式将 st1 修改后的对象写入文件中。

关于java - 通过反序列化代码更改数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49446579/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com