将捆绑包保存到文件

时间:2013-01-10 11:23:18

标签: android

  Bundle bundle;
  //set data to bundle
  //......


  File file = new File(context.getFilesDir().getAbsolutePath()  + "/data/");
                FileOutputStream fos;
                try {
                     fos = new FileOutputStream(file);
                     //fos.write
                     fos.close();
                } catch (FileNotFoundException exp1) {
                    exp1.printStackTrace();
                } catch ( IOException exp2) {
                    exp2.printStackTrace();
                }

我有上述代码。我想要做的就是将捆绑包保存到文件中。我发现方法写了但是我不能传递一个包但只传递一个byte []。我试图将bundle转换为byte []但是我没有成功。我该怎么做才能做到这一点?什么是最有效的方式?

7 个答案:

答案 0 :(得分:4)

没有通用的方法来保存和恢复来自持久存储的捆绑包。这是因为Parcel类不提供任何Android版本兼容性保证。所以我们最好不要序列化它。

但是,如果你真的想要你可以通过Parceable接口searialize Bundle。将bundle转换为Parcel(writeToParcel()/ readFromParcel()),然后使用Parcel的marshall()和unmarshall()方法获取byte []。保存/加载字节数组到文件。但有一天,如果用户将Android操作系统更新为更新版本,您将无法恢复数据。

使用ObjectOutput / InputStream序列化bundle有一种合法但非常粗糙且不可靠的方法。 (获取所有键,迭代键并将可序列化的键=值对保存到文件中,然后从文件中读取key = value对,确定值的类型,通过适当的putXXX(键,值)方法将数据放回Bundle中)但它是不值得)

我建议您将自定义可序列化结构放在Bundle中以存储其中的所有必需值,并从文件中保存/加载此结构。

或者在不使用Bundle的情况下找到更好的方法来管理数据。

答案 1 :(得分:4)

我不喜欢上面评论中的代码格式,所以这就是你如何阅读它:

这样读:

try {
    FileInputStream fis = openFileInput(localFilename);
    byte[] array = new byte[(int) fis.getChannel().size()];
    fis.read(array, 0, array.length);
    fis.close();
    parcel.unmarshall(array, 0, array.length);
    parcel.setDataPosition(0);
    Bundle out = parcel.readBundle();
    out.putAll(out);
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
} finally {
    parcel.recycle();
}

答案 2 :(得分:3)

Bundle in=yourBundle;
FileOutputStream fos = context.openFileOutput(localFilename, Context.MODE_PRIVATE);
Parcel p = Parcel.obtain(); //creating empty parcel object
in.writeToParcel(p, 0); //saving bundle as parcel 
fos.write(p.marshall()); //writing parcel to file
fos.flush();
fos.close();

答案 3 :(得分:0)

你可以做这样的事情

public void write(String fileName, Bundle bundle)
    {
        File root = Environment.getExternalStorageDirectory();
        File outDir = new File(root.getAbsolutePath() + File.separator + "My Bundle");
        if (!outDir.isDirectory())
        {
            outDir.mkdir();
        }
        try
        {
            if (!outDir.isDirectory())
            {
                throw new IOException("Unable to create directory My bundle. Maybe the SD card is mounted?");


    }
        File outputFile = new File(outDir, fileName);
        writer = new BufferedWriter(new FileWriter(outputFile));
        String value=bundle.getString("key");
        writer.write(value);
        Toast.makeText(context.getApplicationContext(), "Report successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
        writer.close();
    } catch (IOException e)
    {
        Log.w("error", e.getMessage(), e);
        Toast.makeText(context, e.getMessage() + " Unable to write to external storage.", Toast.LENGTH_LONG).show();
    }

}

这里的想法很简单。您将Bundle传递给此方法,然后提取您拥有的任何数据(在本例中为示例,我们有一个带有键key的字符串),然后将其写入文件。

答案 4 :(得分:0)

以下是可以帮助您将Bundle转换为JSONObject的功能,请注意,只有在捆绑包含int和仅String的情况下,它才有效/ p>

public static JSONObject bundleToJsonObject(Bundle bundle) {
    try {
        JSONObject output = new JSONObject();
        for( String key : bundle.keySet() ){
            Object object = bundle.get(key);
            if(object instanceof Integer || object instanceof String)
                    output.put(key, object);
            else
                throw new RuntimeException("only Integer and String can be extracted");
        }
        return output;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

public static Bundle JsonObjectToBundle(JSONObject jsonObject) {
    try {
        Bundle bundle = new Bundle();
        Iterator<?> keys = jsonObject.keys();
        while( keys.hasNext() ){
            String key = (String)keys.next();
            Object object = jsonObject.get(key);
            if(object instanceof String)
                bundle.putString(key, (String) object);
            else if(object instanceof Integer)
                bundle.putInt(key, (Integer) object);
            else
                throw new RuntimeException("only Integer and String can be re-extracted");
        }
        return bundle;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

答案 5 :(得分:0)

您无法将捆绑包保存到本地文件中。您将获得非序列化异常。可能还有其他快捷方式存储。阅读和构建原始对象后,不是100%保证。

答案 6 :(得分:0)

我认为最好的想法是静态序列化或一切,因为Bundle可以从密钥迭代,在另一端序列化和反序列化,你可以使用json,或任何东西。例如,如果您将在服务器和接收器中使用相同的类,...

bundle-&GT; serializable_object-&GT; json-&GT;文件 - &GT; serializable_object-&GT;束

任何操作系统版本保证工作

相关问题