【问题标题】:How to test if serializable object exists in storage before reading from it?如何在读取之前测试存储中是否存在可序列化对象?
【发布时间】:2018-07-29 02:27:07
【问题描述】:

我有一个可序列化的对象数据。当我的主要活动加载时,我希望它检查存储中是否有保存的数据实例。如果是这样,读取它并实例化为变量。如果没有,将使用新的数据副本。

我的对象读写代码:

 // Method used to read questions data
    public static void read(){
        FileInputStream fis = null;
        ObjectInputStream in = null;
        try {
            fis = new FileInputStream("SAVED_DATA");
            in = new ObjectInputStream(fis);
            myData = (Data) in.readObject();
            in.close();;
        } catch(Exception e){
            e.printStackTrace();;
        }
    }
    // Method used to write the questions data
    public static void save(){
         FileOutputStream fos = null;
         ObjectOutputStream out = null;
         try{
             fos = new FileOutputStream("SAVED_DATA");
             out = new ObjectOutputStream(fos);
             out.writeObject(myData);
         } catch (Exception e){
             e.printStackTrace();
         }
    }

我的 onCreate() 方法中的代码类似于:

if (read()) { //How to test if a Data object exists?
read(); // Read the object from storage and set variable to the result
       } else {
           myData = new Data(); // There's no stored object so set up a new one
   }

最好(最简单)的方法是什么?

【问题讨论】:

    标签: java android storage serializable


    【解决方案1】:

    不要抓住IOException。让它被扔掉。或者返回一个表示成功或失败的值。

    【讨论】:

    • 我喜欢返回一个指示失败成功的值的想法 - 我将如何将其应用于我的 read() 方法并将其与我的 if 语句结合起来?
    【解决方案2】:

    最后我通过如下修改我的 read() 方法解决了这个用例:

     // Method used to read questions data
        public static void read(File path){
            ObjectInputStream in = null;
            String filename = "SAVED_DATA";
            try {
                in = new ObjectInputStream(new FileInputStream(new File(new File(path, "")+File.separator+filename)));
                myData = (Data) in.readObject();
                in.close();;
                Log.i("dev", "just closed the stream, read successful");
            } catch(Exception e){
                Log.i("dev", "exception with read - about to set to defaul object");
                Log.e("dev", "exception", e);
    
                myData = new Data();
            }
        }
    

    如果读取成功,则使用从存储中读取的对象,如果有错误,则使用新对象:)

    然后只需在 oncreate() 方法中调用 read()。

    【讨论】:

      猜你喜欢
      • 2013-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多