开发者

Saving an int to a file in Android

I have this code I got off dev.android.com..开发者_开发百科.

@Override
    protected void onStop(){
        FileOutputStream fos = openFileOutput(filename, MODE_PRIVATE);
        fos.write(levelComplete);
        fos.close();
    }

Supposedly this should create the file if it's not there, otherwise, it should write to it. However, I'm getting a FileNotFoundException. Help?

EDIT: Input:

@Override
protected void onStart(){
    FileInputStream fis = openFileInput(filename);
    levelComplete = fis.read();
    fis.close();
}


It might not be this that is your problem, but I just want to mention it to be sure:

If you look at the documentation for the openFileOutput (String name, int mode) function, the description for the name parameter says the following:

name: The name of the file to open; can not contain path separators.

Notice in particular the part about can not contain path separators. Many misses out on this one and tries to specify a complete path (such as /sdcard/myapp/myfile.txt), but this is not allowed. Instead you should only specify the name of the file (e.g. myfile.txt).

The reason for this is that openFileOutput opens a stream to a file which is private to your application (and the documentation also says that it will create the file if it doesn't exist). Because of this it will not make any sense to specify a path, since it will reside within your applications private area.


Try the following code :

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

Also, don't forget to put the permissions in manifest file. Something like :

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

This should help !!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜