2

我正在尝试将 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();
}

}

4

1 回答 1

0

您的实施是正确的。但请注意,您必须验证手机或模拟器上是否有 SD 卡。

为方便起见,您可以尝试是否

Environment.getExternalStorageDirectory().getAbsoluteFile()

返回现有文件。

如果文件存在,请检查权限。如果要使用外部存储,AndroidManifest.xml 中需要以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

希望能帮助到你。

于 2012-02-23T02:04:03.510 回答