Den - Ben
Den - Ben

Reputation: 99

Cant write string in new line

I cant write string in file in new line, although i add "\n" to the end of string

public void writeEquation(String fileName, String expr) {     
        File aFile = new File(fileName);
        try {
            FileWriter writer = new FileWriter(aFile, true);
            BufferedWriter buffered = new BufferedWriter(writer);
            buffered.write(expr+"\n");
            buffered.flush();
            buffered.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

where is the mistake?

Upvotes: 1

Views: 1288

Answers (3)

user520288
user520288

Reputation:

Why not use the newLine() method provided by the BufferedWriter class?

Writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.

In your code, change:

 buffered.write(expr+"\n");

to :

 buffered.write(expr);
 buffered.newLine();

Later edit: Also I am not sure where you want the new line, but if you want to make sure that your expr string gets added on a new line at the end of a file, then call the method before calling buffered.write(expr) like:

buffered.newLine();
buffered.write(expr);

Upvotes: 7

ejb_guy
ejb_guy

Reputation: 1125

use BufferedWriter.newLine() method of BufferedWriter. This will help in tiding over the quirks dependent on OS

Upvotes: 2

Subir Kumar Sao
Subir Kumar Sao

Reputation: 8411

Do

buffered.write("\n"+expr);

When you do expr+"\n" you are getting newline after your string.

Upvotes: 0

Related Questions