【发布时间】:2012-08-02 20:38:39
【问题描述】:
我知道有人就这个主题提出/回答了几个问题,但我需要更具体的帮助,因为这是我第一次尝试这样的事情。我已尝试实施这些问题的答案,但仍然有错误。我需要将动态数量的序列化对象写入文件,然后从该文件中读取以检索对象。我正在使用 android 仅供参考。
这是我的 write() 和覆盖的 writeStreamHeader():
//check and see if there is a file already created to hold patterns, if not, make one
//only created once or if file is deleted; append to it if it's already created
if(!new File(getFilesDir()+"/Patterns").exists())
{
try {
fos = new FileOutputStream(getFilesDir()+FILENAME, true);
out = new ObjectOutputStream(fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try {
out = new AppendingObjectOutputStream(fos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//create a pattern of points. Max amount of Patterns is 100.
if(patternindex!=100)
{
Patterns[patternindex] = new Pattern(ActivePoints, name, xshift, yshift, scaling, rotation);
try {
//out.reset();
out.writeObject(Patterns[patternindex]); //write the object
//out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
patternindex++;
dialog.dismiss();
}
public class AppendingObjectOutputStream extends ObjectOutputStream {
public AppendingObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
@Override
protected void writeStreamHeader() throws IOException {
out.reset();
// do not write a header
}
}
我检查该文件是否存在(它确实存在,因为我已经运行了这段代码),然后我的 writeObject() 在创建“特殊”ObjectOutputStream 后使用 NULLPointerException 使程序崩溃。
这是我的反序列化/读取:
String PatternNames[] = new String[2];
Pattern Patterns[] = new Pattern[2];
FileInputStream fis;
ObjectInputStream in;
try {
fis = new FileInputStream(getFilesDir()+"/Patterns");
in = new ObjectInputStream(fis);
for(int i=0;i<2;i++)//just trying to read 2 objects to start with
{
{
Patterns[i] = (Pattern) in.readObject();
PatternNames[i] = Patterns[i].getName();
}
}
in.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
非常感谢任何帮助,因为我花了相当多的时间试图解决这个问题。我知道有些人已经完成了这一切。作为旁注,我已经对保存到不同文件的一个对象进行序列化/反序列化,但考虑到我的项目要求,这几乎没有用。
【问题讨论】:
标签: android object serialization append