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
Click Format > Make plain text (from the top menu).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With