Pizzret
Pizzret

Reputation: 95

Adding new lines of text in a text file

My app records sounds. Once the sound is recorded, user is asked to input a new file name. Now what I'm trying to do next is to add all file names in a text file so that I can read it later as an array to make a listview.

This is the code:

//this is in onCreate
File recordedFiles = new File(externalStoragePath + File.separator + "/Android/data/com.whizzappseasyvoicenotepad/recorded files.txt");
if(!recordedFiles.exists())
    {
            try {
                recordedFiles.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
//this executes everytime text is entered and the button is clicked
try {
            String content = input.getText().toString();
            FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(">" + content + ".mp3");
            bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

Now the problem is that everytime I record a new file, the previous line is overwritten. So if I record two files 'text1' and 'text2', after I've recorded text1, the txt file will show text1, but after I recorded the text2, the text2 will overwrite the text1 instead of inserting a new line.

I tried adding:

bw.NewLine()

before

bw.write(">" + content + ".mp3");

but it doesn't work.

If I record three sounds and name them sound1, sound2 and sound3, I want this to be the result:

>sound1
>sound2
>sound3

Upvotes: 1

Views: 182

Answers (4)

Pshemo
Pshemo

Reputation: 124225

Use FileWriter constructor with boolean append argument

FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile(), true);
//                                                              ^^^^

this will let file append text at the end instead overwriting previous content.

Upvotes: 4

Promille
Promille

Reputation: 105

FileWriter takes a boolean if it should overwrite. So use true if you would like to to append to the file instead of overwrite.

Upvotes: 0

Harish Godara
Harish Godara

Reputation: 2386

Replace

FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile());

Instead of

FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile(), true);

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

You can do it by adding line.separator Property

 bw.write(">" + content + ".mp3");
 bw.write(System.getProperty("line.separator").getBytes());

Upvotes: 0

Related Questions