Android Java——在Android平台上反序列化文件

2024-03-19

我有一个 java 程序,可以序列化稍后存储和读取的文件。因此,我获取序列化文件并尝试使用与 Java SE 中使用的完全相同的代码在我的 Android 手机(在 Eclipse 中工作)上读取它们:


FileInputStream fis = null;
try {
    fis = new FileInputStream("iwastedahalfhouronthis.ser");
   } catch (FileNotFoundException ex) {
}

抛出 FileNotFoundException。好吧,它可能不在正确的位置。因此,我将该文件放置在 Eclipse 项目中每个可能的文件夹中,并尝试从这些位置加载。没有运气。确保文件名正确,没有运气。使用 eclipse 给出的完全限定名称:“/pleasehelp/src/com/imlosingit/iwastedahalfhouronthis.ser”。没有运气。将文件对象传递到 FileInputStream 中。没有运气。这对于 Java 来说是非常简单的。这里发生了什么?

-----------编辑解决方案--------------------


        Data data = null; //object to be deserialized
        InputStream is = null;
        ObjectInputStream ois=null;
        AssetManager assets = getAssets();
        is = assets.open("fff.ser");
        ois = new ObjectInputStream(is);
        data = (com.data.Data) ois.readObject();

查看一些吸气剂Context http://developer.android.com/reference/android/content/Context.html。尝试将文件保存到缓存文件夹,或者如果它们是大文件,您可能需要尝试外部目录(例如 SD 卡)。

File dir = getCacheDir();
//do stuff, saving the file in this directory

FileInputStream fis = null;
try {
    fis = new FileInputStream(new File(dir, "iwastedhalfhouronthis.ser"));
} catch (FileNotFoundException ex) {
}

编辑:阅读您的评论后,我建议将您的序列化文件存储在/assets。然后你可以使用 AssetManager 来检索这些:

AssetManager assets = getAssets();
AssetFileDescriptor afd = assets.openFd("iwastedhalfhouronthis.ser");
FileInputStream fis = afd.createInputStream();

编辑:还要尝试一件事。将 .ser 文件放入名为的新文件夹中/raw(您必须手动创建它),然后尝试以下操作:

Resources res = getResources();
//might need "R.raw.iwastedhalfhouronthis.ser" but I don't think so.
AssetFileDescriptor afd = res.openRawResourceFd(R.raw.iwastedhalfhouronthis);
FileInputStream fis = afd.createInputStream();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android Java——在Android平台上反序列化文件 的相关文章

随机推荐