java - 将多个对象写入和读取到文件

标签 java android file object

我正在为 android 设计一个手写应用程序。

我想在每次用户按下回车按钮时将信息(class LogInfo)写入日志文件。

之后,我想读取存储的信息。

这是我的类的一部分,带有自定义写入方法:

public class LogInfo implements Serializable {

private static final long serialVersionUID = -5777674941129067422L;

public static List<Point[][]> strokes;
public static List<byte[]> codes;

// Only write and read methods shown

private void writeObject(ObjectOutputStream stream) throws IOException
{
    stream.defaultWriteObject();
    stream.writeInt(strokes.size());
    Point[][] pointsArray = null;
    for (int i = 0; i < strokes.size(); i++)
    {
        pointsArray = ((Point[][])strokes.get(i));
        stream.writeInt(pointsArray.length);
        for (int j = 0; j < pointsArray.length; j++)
        {
            stream.writeInt(pointsArray[j].length);
            for (int k = 0; k < pointsArray[j].length; k++)
            {
                stream.writeInt(pointsArray[j][k].x);
                stream.writeInt(pointsArray[j][k].y);
                //stream.writeObject(elementData[i]);
            }
        }
    }

    int size = codes.size();
    stream.writeInt(size);
    for (int i = 0; i < size; i++)
    {
        stream.write(codes.get(i));
    }
}

这是读取方法:

private void readObject(java.io.ObjectInputStream stream)
    {
        stream.defaultReadObject();
        int strokesSize = stream.readInt();
        for (int i = 0; i < strokesSize; i++)
        {
            int arrayXSize = stream.readInt();
            Point[][] points = new Point[arrayXSize][];
            for (int j = 0; j < arrayXSize; j++)
            {
                int arrayYSize = stream.readInt();
                points[j] = new Point[arrayYSize];
                for (int k = 0; k < arrayYSize; k++)
                    points[j][k] = new Point(stream.readInt(), stream.readInt());
            }
            strokes.add(points);
        }

        int codesSize = stream.readInt();
        for (int i = 0; i < codesSize; i++)
        {
            byte[] buffer = new byte[3];
            stream.read(buffer, 0, 3);
            codes.add(buffer);
        }
    }

当我在文件中只保存一个对象时效果很好。当我尝试保存更多时,读取不起作用(它抛出 StreamCorruptedException)。 它在 while 循环中只读取一个对象!

在主类中,我只使用了两个简单的方法:

// WRITE TO FILE
logInfo.writeLog();

// READ FROM FILE
ArrayList<LogInfo> logInfoArrayList = logInfo.readLog();

定义为:

public void writeLog()
{
    File file = new File (Environment.getExternalStorageDirectory().getAbsolutePath(), "data.log");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(file, true);
        //fos = openFileOutput(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data.log", Context.MODE_APPEND);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(this);
        os.close(); 
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public ArrayList<LogInfo> readLog()
{
    ArrayList<LogInfo> logInfoArray = new ArrayList<LogInfo>();

    try{
        File file = new File (Environment.getExternalStorageDirectory().getAbsolutePath(), "data.log");
        FileInputStream fis  = new FileInputStream(file);
        ObjectInputStream reader = new ObjectInputStream(fis);  

        LogInfo tempLogInfo = new LogInfo();
        while((tempLogInfo = (LogInfo)reader.readObject()) != null)
            logInfoArray.add(tempLogInfo);
        reader.close();
    } catch (Exception e) {
     //TODO Auto-generated catch block
     e.printStackTrace();
    }

    return logInfoArray;
}

要求更新:

//We use this class to not write a header in a file that already exist
class MyObjectOutputStream extends ObjectOutputStream {

    public MyObjectOutputStream(OutputStream os) throws IOException {
        super(os);
      }

    @Override
    protected void writeStreamHeader() {}
}

最佳答案

  1. 您不能追加到使用 ObjectOutputStream 创建的现有文件,至少不是不费吹灰之力。关于扩展 ObjectOutputStream 和覆盖 writeStreamHeader() 方法的地方有一个技巧,以免第二次写入流头,但我不赞成它.你真的应该重写整个文件,也许作为一个列表。

  2. 您不需要所有这些代码。只需使 strokescodes 非静态和非 transient ,并摆脱 readObject()writeObject() 方法。

关于java - 将多个对象写入和读取到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16473856/

相关文章:

python - 如何使用二进制文件。覆盖特定字节

c - 输入要写入文件的数据时出错

java - 常规信息模式

java - FileNotFoundException 与 getResources

java - 通过循环添加对象时 ArrayList 不扩展

android - 从特定点动画 View 以填充整个屏幕并将其重新调整回该点

java - 使用 Google Sheets API v4 追加 100 万行并指定单元格位置

android - ListView 中的 textview.setText() 导致强制关闭

java - 错误: "error:cannot resolve symbol ' WebViewClient'

Java打开文件错误: can't find the specified path