我正在处理一个应用程序,我想在文件中有一个ArrayList。我写了两个方法来保存和获取:序列化控制文件
public static boolean saveMetars(Context context, ArrayList<Metar> metars) {
try {
FileOutputStream fos = context.openFileOutput("metars_array", Context.MODE_WORLD_READABLE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(metars);
oos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static ArrayList<Metar> getArrayMetars(Context context) {
try {
Log.d("here", "asas");
FileInputStream fis = context.openFileInput("metars_array");
ObjectInputStream is = new ObjectInputStream(fis);
Object readObject = is.readObject();
is.close();
if(readObject != null && readObject instanceof ArrayList) {
Log.d("here2", "asas");
return (ArrayList<Metar>) readObject;
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
我的问题是:当用户安装该应用程序,并使用它的第一次,我有一个XML文件,我用一个方法(在创建了APPI)读取并创建METAR对象添加到我的ArrayList ..问题是,我想有一个if语句或类似的东西,控制如果文件
context.openFileOutput(“metars_array” Context.MODE_WORLD_READABLE) 存在。
我制成
if(getApplicationContext().getDir("metars-array", MODE_WORLD_READABLE).exists() || getBaseContext().getDir("metars-array", MODE_WORLD_READABLE).exists()){
ArrayList<Metar> mets = getArrayMetars(getBaseContext());
isMetarsInDb=true;
}
else
isMetarsInDb=false;
该错误是,它总是在第一条目是否,当我做
ArrayList的METS = getArrayMetars(getBaseContext());
它返回一个错误说
文件 “/data/data/android.altimeter.com/app_metars_array”(文件未找到 )
我想这样做,因为如果文件不存在(用户第一次使用该应用程序,他从未序列化ArrayList),我必须使用从XML读取的方法,然后序列化为metars_array文件。
我已经解决了这个问题;) – cpfp
大。如果这个评论是答案,请随时标记这个答案。谢谢! –