I'm trying to save int values inside a text file on external storage. When I tried to use the saveAudio() function, I get a FileNotFoundException. What am I doing wrong? I'm running the program in an android emulator.
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();
}
}
Your implementation is right. But notice that you have to verify that a SD card is available on your phone or emulator.
To make it easier, you can try whether
Environment.getExternalStorageDirectory().getAbsoluteFile()
returns existing file.
If the file exists, check the permission. Following permission is needed in AndroidManifest.xml, if you want to use external storage:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.