reissigree
reissigree

Reputation: 1

Why won't this create a new line in a text file in Android?

This is a method in my Android app that should create a new line in the text file before a new String text is added. However, when it runs, There is no new line.

    public void addTextToFile(String text) {
    try
    {
        File log=new File(getFilesDir()+File.separator+"MileageLog.txt");

        BufferedWriter bufferedWriter=null;
        if(log.exists()==false)
        {
            bufferedWriter = new BufferedWriter(new FileWriter(log+"\n"));


        }else{
            bufferedWriter = new BufferedWriter(new FileWriter(log+"\n", true));

        }
        String[] lines=text.split("\n");
        for(String line:lines)
        {
            bufferedWriter.write(line);

        }
        bufferedWriter.close();
        Toast.makeText(getBaseContext(), "Added Successfully", Toast.LENGTH_SHORT).show();
        finish();
    }catch(IOException ex)
    {
        ex.printStackTrace();

    }

Upvotes: 0

Views: 203

Answers (2)

Jigar Joshi
Jigar Joshi

Reputation: 240870

Because you are not writing new line character (you are actually splitting text by new line character so there is no new line character in your lines)

change it to

bufferedWriter.write(line);
bufferedWriter.newLine();

if you want to add new line after each line

Upvotes: 1

Alistair
Alistair

Reputation: 641

You can also use the newLine() method that will write a line separator. For further details, check the link: Android BufferedWriter

Upvotes: 1

Related Questions