0

好吧,基本上我想这样做,

class myclass
{
    int a1;
    float b1;
    char c1;     //This is a single character
}
List<myclass> obs;

现在在运行时,这个 obs 变量,因为它是一个列表,将包含我们得到其大小的 myclass 实例的数组obs.size();

那么,如何使用 OutputStream 或类似的东西将这些数据写入文件说“data1.bin”作为二进制文件。但这要在 Android 操作系统中完成。

我在 C++ 中做了类似的事情

class myclass
{
    int a1;
    float b1;
    char c1;
}

myclass student1;

ofstream output_file("students.data", ios::binary);
output_file.write((char*)&student1, sizeof(student1));
output_file.close()

但是如何在 Android 操作系统中做到这一点?

4

1 回答 1

0

如果你想将你的类转储到文件中,让类实现 Serializable 和 java(或 android 上的 Dalvik VM)将在幕后为你做这件事。

class MyClass implements Serializable {

    private static final long serialVersionUID = 1L;

    int a1;
    float b1;
    char c1;     //This is a single character
}


private File file;
private MyClass myClass;

private void writeIt() throws IOException {

    ObjectOutputStream stream = null;
    try {
        stream = new ObjectOutputStream(new FileOutputStream(file));
        stream.writeObject(myClass);
    } 
    finally {
        if(stream != null) {
            stream.close();
        }
    }
}

private MyClass readIt() throws IOException, ClassNotFoundException {

    ObjectInputStream stream = null;
    try {
        stream = new ObjectInputStream(new FileInputStream(file));
        return (MyClass) stream.readObject();
    } 
    finally {
        if(stream != null) {
            stream.close();
        }
    }
}
于 2012-04-21T16:35:17.980 回答