java - 将类类型信息保存到文件以备后用

标签 java android

如您所知,在编写 Android 应用程序时传递类类型很重要。 一个简单的示例是使用 Intent。

Intent i = new Intent(this, MyActivity.class);

所以在某些情况下,如果我可以将类类型信息保存到文件中供以后使用,例如,在重新启动后使用,它会很有用。

void saveClassTypeInfo(Class<?> classType, String filename) {

String str = null;

// Some job with classType

FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(filename);
        fos.write(str.getBytes());
        fos.close();
    } catch (Exception e) {
    }
}

如果我能像上面那样以某种方式保存,那么我将来就能把它放回这样的 Intent 中。

Intent i = new Intent(this, restoredClassInfoFromFile);

我怎样才能得到这样的工作?因为Class<?>不是一个对象,我根本不知道从哪里开始。

[编辑] .class 也是一个对象,所以我们可以像保存对象一样保存它。

最佳答案

这可以使用 ObjectOutputStream 这里 SaveState 是您的自定义类

public static void saveData(SaveState instance){
ObjectOutput out;
try {
     File outFile = new File(Environment.getExternalStorageDirectory(), "appSaveState.ser");
     out = new ObjectOutputStream(new FileOutputStream(outFile));
     out.writeObject(instance);
     out.close();
 } catch (Exception e) {e.printStackTrace();}
}

public static SaveState loadData(){
 ObjectInput in;
 SaveState ss=null;
 try {
     in = new ObjectInputStream(new FileInputStream("appSaveState.ser"));       
     ss=(SaveState) in.readObject();
     in.close();
 } catch (Exception e) {e.printStackTrace();}
 return ss;
}

写入文件的完整教程可用 here 并从文件中读取对象 here

关于java - 将类类型信息保存到文件以备后用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40180144/

相关文章:

java - 使用 FieldMethodizer 访问静态文件打印 "Could not add x for field methodizing: x"

java - 无法将项目列表发送到后端以从列表中删除

java - Eclipse 插件在调试时有效,但在安装时无效

Java 在 Netbeans 中导入 org-jdesktop-layout

android - 调用需要 API 级别 24(当前最小值为 8): new android. location.GnssStatus.Callback

android - 当可见性从 GONE 变为 VISIBLE 时,TabLayout 文本消失

android - 使用 python 创建一个在后台运行的 android 服务

java - 试图记住疯狂的java数组技巧

android - IntentService 不会与 PendingIntent 一起调用

android - 如何查看默认的android simple_spinner_dropdown_item 样式