0
我知道这个主题有一些问题需要回答,但我需要更具体的帮助,因为这是我第一次尝试这样的事情。我试图实现这些问题的答案,但仍然有错误。我需要将一个动态数量的序列化对象写入文件,然后从该文件中读取以检索对象。我正在使用android的FYI。覆盖writeStreamHeader()将序列化对象附加到单个文件
这是我写()和重载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();
}
任何帮助是极大的赞赏,因为我已经花了很多时间相当试图弄清楚这一点。我知道有些人已经完成了整个工作。作为一个方面说明,我已经获得序列化/反序列化处理一个对象保存到不同的文件,但这是最没有用的,因为我的项目需求。
发布堆栈跟踪。 – EJP 2012-08-05 09:49:14