Android Java – 反序列化Android平台上的文件

我有一个jave程序,它序列化存储和稍后读取的文件。 所以我采用序列化文件并尝试使用我在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一些getter。 尝试将文件保存到缓存文件夹,或者如果它们将是大文件,您可能需要尝试外部目录(例如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(); 

看看这里 – 序列化文件应该转到/data/data/APP_PACKAGE/iwastedahalfhouronthis.ser

将文件放在/ res / assets目录中。 然后,您可以使用Context.getAssets()返回AssetManager实例以处理assets目录中的文件。

我认为我们有类似的情况,其中javaSe应用程序生成二进制文件,Android必须读取它。

这就是我做到的。 首先将文件放在res / raw中

  Resources res = getResources(); InputStream is = res.openRawResource(R.raw.kasalvage); ObjectInputStream ois =new ObjectInputStream(is); //Blueprint is my custom object bp = (BlueprintMap)ois.readObject(); Toast.makeText(this, bp.getTitle(), 2000).show(); 

我必须创建一个包含BlueprintMap类模型的Jar库,并将其导入到桌面应用程序和Android应用程序的项目中,它消除了ClassNotFoundException。 我希望这有帮助