2

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

}

iamarnold
  • 705
  • 1
  • 8
  • 22

1 Answers1

0

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.

Davidsun
  • 721
  • 6
  • 13