New line writing to a file

Dayerman picture Dayerman · Feb 8, 2011 · Viewed 14.4k times · Source

I am trying to write to a file the log of my application. I have created an method which appends a line to the end of the line.

    public static void write2Log(String s){
    StringBuilder contents = new StringBuilder();
    File root = Environment.getExternalStorageDirectory();
    File logFile = new File(root, "testWrite2file.log");

    if (root.canWrite()){               
        try {
            BufferedReader input =  new BufferedReader(new FileReader(logFile));
            String line = null;                            
            while (( line = input.readLine()) != null){
              contents.append(line);
             // contents.append(System.getProperty("line.separator"));            
        }
        input.close();
        FileWriter logWriter = new FileWriter(logFile);                  
        BufferedWriter out = new BufferedWriter(logWriter); 
        out.write(contents.toString()+"\r\n"+s);////<---HERE IS MY QUESTION
        out.close();
        }

        catch (IOException e) {
            Log.e("test", "Could not read/write file " + e.getMessage());
        }
    }
}

Everything works fine less the new character line.

I have tried using:

\r\n

System.getProperty("line.separator")

newline()

But i keep getting all in just one line :(

Any ideas?

Answer

abhi picture abhi · Dec 17, 2014

Try this:

FileWriter logWriter = new FileWriter(logFile);                  
BufferedWriter out = new BufferedWriter(logWriter); 
out.write(contents.toString());////<---HERE IS THE CHANGE
out.newLine();
out.write(s);
out.close();