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();
}

この問題の理由は何ですか?
私はエミュレーターで実行していて、アプリケーションはandroid3.0です。

4

3 に答える 3

0

私が間違っている場合は訂正してください。ただし、書き込む前にファイルを作成する必要はありませんか?

File file = new File(dir, FILE_NAME);
if (!file.exists()) {
    file.createNewFile();
}
于 2012-06-18T09:33:24.303 に答える
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 に答える
0

ファイル名が無効であると思われます。ディレクトリに?またはファイル名自体。

于 2012-06-18T09:51:29.223 に答える