我正试图将int值保存在外部存储的文本文件中。当我尝试使用saveAudio()函数时,我得到了一个FileNotFoundException。我做错了什么?我正在安卓模拟器中运行该程序。
File externalStorageDir = new File (Environment.getExternalStorageDirectory().getAbsoluteFile(),"audiosettings.txt");
/**Stores the game volume level*/
int gameVolume_level;
/**Stores the music volume level*/
int musicVolume_level;
/**Stores the GUI volume level*/
int guiVolume_level;
private void loadAudio() {
try {
DataInputStream dis = new DataInputStream(new FileInputStream(externalStorageDir));
gameVolume_level = dis.readInt();
dis.readChar();
musicVolume_level = dis.readInt();
dis.readChar();
guiVolume_level = dis.readInt();
dis.readChar();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void saveAudio() {
DataOutputStream dos;
try {
dos = new DataOutputStream(new FileOutputStream(externalStorageDir));
dos.writeInt(gameVolume_level);
dos.writeChar('t');
dos.writeInt(musicVolume_level);
dos.writeChar('t');
dos.writeInt(guiVolume_level);
dos.writeChar('n');
dos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
您的实现是正确的。但请注意,您必须验证您的手机或模拟器上是否有SD卡。
为了更容易,你可以试试
Environment.getExternalStorageDirectory().getAbsoluteFile()
返回现有文件。
如果文件存在,请检查权限。如果你想使用外部存储,AndroidManifest.xml中需要以下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
希望能有所帮助。