1

我想序列化一个对象并将其存储sdcard在我的项目名称下,但我得到FileNotFoundException.

我的代码写在下面:

FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;

File dir = new File(Environment.getExternalStorageDirectory(), FILE_LOCATION + username);

try {
    if(!dir.exists()) {
        dir.mkdirs();
    }
    File file = new File(dir, FILE_NAME);
    fileOutputStream = new FileOutputStream(file);
    objectOutputStream = new ObjectOutputStream(fileOutputStream);
    objectOutputStream.writeObject(formList);
    objectOutputStream.close();
} catch(IOException ioException) {
    ioException.getMessage();
} catch (Exception e) {
    e.getMessage();
}

这个问题的原因是什么?
我在模拟器中运行,我的应用程序在 android 3.0 中。

4

3 回答 3

0

如果我错了,请纠正我,但是您不必在写入文件之前创建文件吗?

File file = new File(dir, FILE_NAME);
if (!file.exists()) {
    file.createNewFile();
}
于 2012-06-18T09:33:24.303 回答
0

我怀疑您的文件名无效,也许是 . 在目录中?或文件名其自身。

于 2012-06-18T09:51:29.223 回答
0

我想分享我的解决方案,因为我从 Stackoverflow 获得了很多关于这个问题的帮助(通过搜索以前的答案)。我的解决方案经过几个小时的搜索和拼凑解决方案。我希望它可以帮助某人。

这将在外部存储中写入和读取自定义对象的 ArrayList。

我有一个为我的活动和其他课程提供 IO 的课程。警报是我的自定义类。

@SuppressWarnings("unchecked")
public static ArrayList<Alarm> restoreAlarmsFromSDCard(String fileName,
        Context context) {

FileInputStream fileInputStream = null;

ArrayList<Alarm> alarmList = new ArrayList<Alarm>();//Alarm is my custom class
//Check if External storage is mounted
if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
                "YourAppName/DesiredDirectory");

try {
if (!dir.exists()) {
Log.v("FileIOService", "No Such Directory Exists");
}
File file = new File(dir, fileName);
fileInputStream = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fileInputStream);
alarmList = (ArrayList<Alarm>) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
//Do something here to warn user
}

return alarmList;
}

public static void saveAlarmsToSDCard(String fileName, ArrayList<Alarm>     alarmList,Context context) {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;

if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
                "YourAppName/DesiredDirectory");

try {
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, fileName);
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(alarmList);
objectOutputStream.close();
} catch (IOException ioException) {
ioException.getMessage();
} catch (Exception e) {
e.getMessage();
}
}else{
//Do something to warn user that operation did not succeed
}

}
于 2013-05-03T13:21:26.127 回答