使用反序列化从文本文件导入数据,但文本未显示在文本字段中
Importing data from a text file using deserialization but text is not showing in the text fields
我首先将文本字段中的数据导出到文本文件。为此,我使用了序列化。这是代码
public void save()
{
try {
File selectedFile = new File(ConsultantID + ".txt");
FileOutputStream fileStream = new FileOutputStream(selectedFile);
ObjectOutputStream oos = new ObjectOutputStream(fileStream);
oos.writeObject(this);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
private String toString(int ConsultantID) {
throw new UnsupportedOperationException("Not supported yet.");
}
要从文件中加载数据,我正在使用反序列化。下面是我为此使用的代码
public static Consultant load()
{
Consultant load = null;
JFileChooser chooser = new JFileChooser();
int chooserOption = chooser.showSaveDialog(null);
chooserOption = JFileChooser.APPROVE_OPTION;
try {
File file = new File (chooser.getSelectedFile().getAbsolutePath());
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
load = (Consultant) input.readObject();
input.close();
return load;
} catch (IOException ex) {
System.out.println(ex.getMessage());
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
return null;
我没有错误,文件加载器正在显示。但是当我 select 文件时,程序不会将数据放入文本字段。我使用以下代码创建了一个加载按钮:
Consultant consl = new Consultant();
this.jTextField1.setText(consl.getConsfirstname());
this.jTextField2.setText(consl.getConslastname());
this.jTextField3.setText(consl.getConsultantID());
consl.load()
你认为我在代码中遗漏了什么吗?
一对夫妇。
- 您似乎在加载数据之前设置了标签的文本。
- 您加载数据,然后丢弃返回的对象。
我建议你先加载数据,然后使用对象的load()函数returns设置值。
我首先将文本字段中的数据导出到文本文件。为此,我使用了序列化。这是代码
public void save()
{
try {
File selectedFile = new File(ConsultantID + ".txt");
FileOutputStream fileStream = new FileOutputStream(selectedFile);
ObjectOutputStream oos = new ObjectOutputStream(fileStream);
oos.writeObject(this);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
private String toString(int ConsultantID) {
throw new UnsupportedOperationException("Not supported yet.");
}
要从文件中加载数据,我正在使用反序列化。下面是我为此使用的代码
public static Consultant load()
{
Consultant load = null;
JFileChooser chooser = new JFileChooser();
int chooserOption = chooser.showSaveDialog(null);
chooserOption = JFileChooser.APPROVE_OPTION;
try {
File file = new File (chooser.getSelectedFile().getAbsolutePath());
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
load = (Consultant) input.readObject();
input.close();
return load;
} catch (IOException ex) {
System.out.println(ex.getMessage());
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
return null;
我没有错误,文件加载器正在显示。但是当我 select 文件时,程序不会将数据放入文本字段。我使用以下代码创建了一个加载按钮:
Consultant consl = new Consultant();
this.jTextField1.setText(consl.getConsfirstname());
this.jTextField2.setText(consl.getConslastname());
this.jTextField3.setText(consl.getConsultantID());
consl.load()
你认为我在代码中遗漏了什么吗?
一对夫妇。
- 您似乎在加载数据之前设置了标签的文本。
- 您加载数据,然后丢弃返回的对象。
我建议你先加载数据,然后使用对象的load()函数returns设置值。