【问题标题】:Save to File a Vector of Vector保存到文件矢量的矢量
【发布时间】:2013-12-29 16:09:21
【问题描述】:

我写信给你一个我无法解决的问题。 我有一个向量的向量。

Vector<Vector<Item>> vectorItem;

我不知道如何将其保存到文件中,然后如何加载。

我试试这个:

public void save(String name, Context ctx, Vector<Vector<Item>> vectorItem) {
        try {
            String sdCard = Environment.getExternalStorageDirectory().toString();
            File dir = new File(sdCard + "/dir");
            File file = new File(dir.getAbsolutePath(), name);
            if(!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = ctx.openFileOutput(name, Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(vectorItem);
            oos.close();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }

    public Vector<Vector<Item>> load(String name, Context ctx) {        
        Vector<Vector<Item>> vectorItem; = null;
        String sdCard = Environment.getExternalStorageDirectory().toString();
        File dir = new File(sdCard + "/dir");
        try {
            FileInputStream fis = ctx.openFileInput(name);
            ObjectInputStream ois = new ObjectInputStream(fis);
            vectorItem = (Vector<Vector<Item>>) ois.readObject();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
        catch(ClassNotFoundException e) {
            e.printStackTrace();
        }
        return vectorSezioni;
    }

但这是错误: 12-29 16:57:07.140: W/System.err(32681): java.io.IOException: open failed: ENOENT (没有这样的文件或目录)

【问题讨论】:

  • 第一种方法:保存时序列化,加载时反序列化;第二种方法:将第一个向量值保存在行上,第二个向量值用分隔标记,,; 分隔。
  • 只是吹毛求疵,但 Vector 是一个遗留类。如果您必须进行同步,请使用 Collections.synchronizedList,否则只需使用 ArrayList。此外,通过接口而不是实现来引用对象。所以使用 List>

标签: android file object vector storage


【解决方案1】:

首先,您必须保证您拥有 WRITE_EXTERNAL_STORAGE 权限,因为您正在写入 SD 卡。

调用前

File file = new File(dir.getAbsolutePath(), name);

你应该打电话

dir.mkdirs();

确保目录被创建。

然后,在将对象写入输出流之后,您必须刷新它,以便在其关闭之前写入所有数据

oos.flush();

反序列化方法应考虑目录和文件名:

public Vector<Vector<Item>> load(String name, Context ctx) {        
    Vector<Vector<Item>> vectorItem; = null;
    String sdCard = Environment.getExternalStorageDirectory().toString();
    File dir = new File(sdCard + "/dir");
    File file = new File(dir.getAbsolutePath(), name);
    try {
        FileInputStream fis = ctx.openFileInput(file);
        ObjectInputStream ois = new ObjectInputStream(fis);
        vectorItem = (Vector<Vector<Item>>) ois.readObject();
    }
    catch(IOException e) {
        e.printStackTrace();
    }
    catch(ClassNotFoundException e) {
        e.printStackTrace();
    }
    return vectorSezioni;
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 2014-01-26
    • 2013-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2012-05-16
    相关资源
    最近更新 更多