G Cox
G Cox

Reputation: 23

Android Studio write to .properties file

I followed Where to put own properties file in an android project created with Android Studio? and I got an InputStream which reads from my .properties file successfully. However, I can't write to that .properties file, as there is no similar method to getBaseContext().getAssets().open ("app.properties") which returns an OutputStream. I have also read Java Properties File appending new values but this didn't seem to help me, my guess is my file name for the file writer is wrong but I also tried "assets\userInfo.properties" which also doesn't work.

My .properties file is in src\main\assets\userInfo.properties

    Properties props = new Properties();
    InputStream inputStream = null;
    try{
        inputStream = getBaseContext().getAssets().open("userInfo.properties");
        props.load(inputStream);

        props.put("name", "smith");
        FileOutputStream output = new FileOutputStream("userInfo.properties"); //this line throws error
        props.store(output, "This is overwrite file");

        String name = props.getProperty("name");
        Log.d(TAG, "onCreate: PROPERTIES TEST NAME CHANGE: " + name);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Current code throws this error:

java.io.FileNotFoundException: userInfo.properties (Read-only file system)

Upvotes: 2

Views: 1838

Answers (2)

Christine
Christine

Reputation: 5575

You can't write to the assets folder. If you want to update your properties file, you'll have to put them some place else. If you want the initial version in the assets or raw folder, just copy it to the default files dir when the app is first used, then read from/write to it there.

Upvotes: 1

Zoe - Save the data dump
Zoe - Save the data dump

Reputation: 28228

You can't write to the assets folder, as it is inside the APK which is read-only.

Use internal or external storage instead

Upvotes: 3

Related Questions