我有一个 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
中的一些 setter/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();
关于java - Android Java -- 在Android平台反序列化一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5795410/