我想做什么
- 模拟一个社交网络程序,您可以在其中添加您的个人资料、更改您的状态、您的图片、添加 friend 等。该程序必须在关闭文件之前保存其内容。
我打算怎么做
- 因为我无法附加 ObjectOutputStream。我想创建一个
ArrayList<SocialProfiles>
(SocialProfiles) 在本例中是我要保存的个人资料。 - 我想在程序启动时将配置文件从文件加载到 ArrayList,当我添加完配置文件后,我想将配置文件从 ArrayList 写回文件。
- 我使用数组的大小作为索引。例如,当它第一次写入数组时,它会写入索引 0。当它有 1 个元素时,它会写入索引 1 等等。
什么事情没有按预期进行?
- 程序不会将数据从文件加载到数组。
我在 Main 打电话什么
try {
fileoutput = new FileOutputStream("database.dat");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
output = new ObjectOutputStream(fileoutput);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fileinput = new FileInputStream("database.dat");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
System.out.println("File database.dat nuk ekziston");
}
try {
input = new ObjectInputStream(fileinput);
} catch (IOException e2) {
}
loadData();
frame.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
new Thread()
{
@Override
public void run()
{
writeData();
try {
fileinput.close();
fileoutput.close();
input.close();
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
}.start();
}
});
方法
public void loadData(){
try{
while (true)
{
SocialProfile temp;
temp = (SocialProfile)input.readObject();
profiles.add(profiles.size(),temp);
}
}
catch(NullPointerException e){
}
catch(EOFException e){
System.out.println("U arrit fund-i i file");
} catch (ClassNotFoundException e) {
System.out.println("Objekt-i i lexuar nuk u konvertua dot ne klasen e caktuar");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeData(){
SocialProfile temp;
for(int i=0;i<profiles.size();i++){
temp=profiles.get(i);
try {
output.writeObject(temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最佳答案
尝试序列化/反序列化整个数组而不是每个对象。
public void serializeData(String filename, ArrayList<SocialProfile>arrayList) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayList);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
...
}catch(IOException e){
...
}
}
private ArrayList<SocialProfile> deserializeData(String filename){
try{
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
return (ArrayList<SocialProfile>)ois.readObject();
} catch (FileNotFoundException e) {
...
}catch(IOException e){
...
}catch(ClassNotFoundException e){
...
}
}
关于java - 使用 ObjectInputStream、ObjectOutputStream 时程序无法正确加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20881157/