我正在尝试将 int 值保存在外部存储上的文本文件中。当我尝试使用 saveAudio() 函数时,我得到一个 FileNotFoundException。我究竟做错了什么?我正在 android 模拟器中运行该程序。
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" />
希望对您有所帮助。
关于java - Android:DataInputStream 和 DataOutputstream 看不到我的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9405202/