Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how to write formatted output to plain text file

Tags:

java

I am developing a small java application. At some point i am writing some data in a plain text file. Using the following code:

Writer Candidateoutput = null;
File Candidatefile = new File("Candidates.txt"),
Candidateoutput = new BufferedWriter(new FileWriter(Candidatefile));
Candidateoutput.write("\n Write this text on next line");
Candidateoutput.write("\t This is indented text");
Candidateoutput.close();

Now every thing goes fine, the file is created with the expected text. The only problem is that the text was not formatted all the text was on single line. But if I copy and paste the text in MS Word then the text is formatted automatically.

Is there any way to preserver text formatting in Plain text file as well?

Note: By text formatting I am referring to \n and \t only

like image 363
Jame Avatar asked Aug 23 '11 07:08

Jame


People also ask

How do you format plain text?

Click Format > Make plain text (from the top menu).

How do you write multiple lines in a text file in Java?

BufferedWriter can be used to write string to file. boolean append = true; String filename = "/path/to/file"; BufferedWriter writer = new BufferedWriter(new FileWriter(filename, append)); // OR: BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append))); writer.


2 Answers

Use System.getProperty("line.separator") for new lines - this is the platform-independent way of getting the new-line separator. (on windows it is \r\n, on linux it's \n)

Also, if this is going to be run on non-windows machines, avoid using \t - use X (four) spaces instead.

like image 172
Bozho Avatar answered Oct 12 '22 19:10

Bozho


You can use line.separator system property to solve your issue.

E.g.

String separator = System.getProperty("line.separator");

Writer Candidateoutput = null;
File Candidatefile = new File("Candidates.txt"),
Candidateoutput = new BufferedWriter(new FileWriter(Candidatefile));
Candidateoutput.write(separator + " Write this text on next line");
Candidateoutput.write("\t This is indented text");
Candidateoutput.close();

line.separator system property is a platform independent way of getting a newline from your environment.

like image 42
Buhake Sindi Avatar answered Oct 12 '22 20:10

Buhake Sindi