我想做什么
模拟一个社交网络程序,您可以在其中添加个人资料,更改状态,您的图片,添加朋友等。该程序必须先保存其内容,然后再关闭文件。
我打算怎么做
由于我不能追加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){
...
}
}