user3503665
user3503665

Reputation: 3

Android: How to write to a certain line, Java

Hello guys and thanks,

I am wondering how do I write to a certain line in java with android. Here is my write method:

    public void saveLesson(int lessons2, int problem2, int mlessons2, int mproblem2, String checkAccuracy) {

    String newline = System.getProperty("line.separator");
    final String saved = new String(lessons2 + newline + problem2 + newline + mlessons2 + newline + mproblem2 + newline + checkAccuracy); 
        FileOutputStream fOut = null;
        try { // catches IOException below        
        fOut = openFileOutput("lessonStore.properties",
                Context.MODE_PRIVATE);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
        OutputStreamWriter osw = new OutputStreamWriter(fOut); 

        // Write the string to the file
        try {
            osw.write(saved);
        /* ensure that everything is
         * really written out and close */
        osw.flush();
        osw.close();
        } catch (IOException e) {

            Toast andEggs = Toast.makeText(Lessons.this, "Error while writing...", Toast.LENGTH_SHORT);
            andEggs.show();
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

How would I make it just overwrite line 3, instead of the whole thing because this is to save variables and it would be nice to just have to save one instead of them all.

Upvotes: 0

Views: 47

Answers (1)

fge
fge

Reputation: 121720

How would I make it just overwrite line 3

you don't!

NEVER modify a file in line; what if your line is shorter than the original? What if it's longer? the OS won't automagically expand/shrink the file for you!

Write contents to another file, then replace the original.

Upvotes: 1

Related Questions