Android - 如何将对象序列化和反序列化到公共(public)外部存储或从公共(public)外部存储中反序列化对象?

标签 android serialization save android-sdcard android-file

我需要将一个对象保存到公共(public)外部存储 ( http://developer.android.com/guide/topics/data/data-storage.html#filesExternal ) 请向下滚动到“保存应该共享的文件”,即保存文件,以便在卸载应用程序时不会被删除。

保存后,我需要从保存的文件中加载对象并显示它。仅将 int 对象用于测试目的。请帮忙。

这是我保存和加载的代码

int a = 1;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
    String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
    final File file = new File (path, "int_object_saved.dat");

    FileOutputStream file_output_stream = null;
    ObjectOutputStream object_output_stream = null;
    boolean should_keep_file = true;

    try
    {
        file_output_stream = new FileOutputStream(file);
        object_output_stream = new ObjectOutputStream(file_output_stream);
        object_output_stream.writeObject(a);

    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
        should_keep_file = false;
    }
    catch (IOException e)
    {
        e.printStackTrace();
        should_keep_file = false;
    }
    finally
    {
        try
        {
            if(object_output_stream != null)
                object_output_stream.close();

            if(file_output_stream != null)
                file_output_stream.close();

            if(!should_keep_file)
                file.delete();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
else
{
    Log.d("mytag", "Sorry can't write to external media");
}

int b = 0;
try
{
    FileInputStream file_input_stream;
    file_input_stream = activity_parameter.openFileInput("int_object_saved.dat");
    ObjectInputStream object_input_stream = new ObjectInputStream(file_input_stream);
    b = (Integer) object_input_stream.readObject();
    object_input_stream.close();
}
catch (FileNotFoundException e)
{
    e.printStackTrace();
}
catch (OptionalDataException e)
{
    e.printStackTrace();
}
catch (ClassNotFoundException e)
{
    e.printStackTrace();
}
catch (IOException e)
{
    e.printStackTrace();
}

Log.d("mytag", Integer.toString(b));

这是我得到的 logcat

08-02 12:39:48.382: I/ApplicationPackageManager(13109): cscCountry is not German : BTU
08-02 12:39:48.421: D/mytag(13109): my Log is working :D
08-02 12:39:48.437: W/System.err(13109): java.io.FileNotFoundException: /data/data/j.violajones.facedetect1/files/int_object_saved.dat (No such file or directory)
08-02 12:39:48.437: W/System.err(13109): at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
08-02 12:39:48.437: W/System.err(13109): at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
08-02 12:39:48.437: W/System.err(13109): at java.io.FileInputStream.<init>(FileInputStream.java:80)
08-02 12:39:48.437: W/System.err(13109): at android.app.ContextImpl.openFileInput(ContextImpl.java:416)
08-02 12:39:48.437: W/System.err(13109): at android.content.ContextWrapper.openFileInput(ContextWrapper.java:152) 
08-02 12:39:48.437: W/System.err(13109): at j.violajones.facedetect1.Detector.<init>(Detector.java:94) 
08-02 12:39:48.437: W/System.err(13109): at j.violajones.facedetect1.Camera_Activty.onCreate(Camera_Activty.java:72)
08-02 12:39:48.437: W/System.err(13109): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-02 12:39:48.437: W/System.err(13109): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
08-02 12:39:48.437: W/System.err(13109): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
08-02 12:39:48.437: W/System.err(13109): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-02 12:39:48.437: W/System.err(13109): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
08-02 12:39:48.437: W/System.err(13109): at android.os.Handler.dispatchMessage(Handler.java:99)
08-02 12:39:48.437: W/System.err(13109): at android.os.Looper.loop(Looper.java:130)
08-02 12:39:48.437: W/System.err(13109): at android.app.ActivityThread.main(ActivityThread.java:3687)
08-02 12:39:48.445: W/System.err(13109): at java.lang.reflect.Method.invokeNative(Native Method)
08-02 12:39:48.445: W/System.err(13109): at java.lang.reflect.Method.invoke(Method.java:507)
08-02 12:39:48.445: W/System.err(13109): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-02 12:39:48.445: W/System.err(13109): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-02 12:39:48.445: W/System.err(13109): at dalvik.system.NativeStart.main(Native Method)
08-02 12:39:48.445: D/mytag(13109): 0

这是我的 AndroidManifest.xml 文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="j.violajones.facedetect1"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Camera_Activty"
            android:label="@string/title_activity_camera__activty"
            android:screenOrientation="landscape" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

最佳答案

错误信息很清楚:

java.io.FileNotFoundException: /data/data/j.violajones.facedetect1/files/int_object_saved.dat (No such file or directory)

/data/data/j.violajones.facedetect1/files/int_object_saved.dat 中没有这样的文件

事实上你似乎并没有写到那个位置,因为你使用:

String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
final File file = new File (path, "int_object_saved.dat");

因此尝试从保存它的位置读取:

String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
FileInputStream file_input_stream = new FileInputStream(path + "/int_object_saved.dat");
/*...*/

关于Android - 如何将对象序列化和反序列化到公共(public)外部存储或从公共(public)外部存储中反序列化对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11776715/

相关文章:

python - 在 Django Rest Framework 中使用嵌套序列化程序进行序列化程序字段验证

java - 可序列化和外部化之间的性能差异 (Java)

java - 使用 JGraphx 在 xml 文件中保存和加载图形

php - 保存前获取用户上传的文件内容

android - 如何从数组列表中隐藏 2 个不正确的答案并启用 2 个可能的答案?

android - localeAwareCompare 的不同结果

android - appcompat_v7 错误

java - 让我的 Android Activity 都可以访问的管理器类处理缓存/数据的基本方法?

serialization - REDIS 中 HMSET 的 RESP 格式

android.database.sqlite.SQLiteException : near "": syntax error