简体   繁体   中英

Inserting New Lines when Writing to a Text File in Java

I have a slight delema with learning FileWriter... The ultimate goal is writing a program that will "spawn" a .bat file that will be executed by the batch code that launched the .jar. The problem is, I have no clue how to make sure that every FileWriter.write(); will print on a new line... Any ideas??

To create new lines, simply append a newline character to the end of the string:

FileWriter writer = ...
writer.write("The line\n");

Also, the PrintWriter class provides methods which automatically append newline characters for you ( edit: it will also automatically use the correct newline string for your OS):

PrintWriter writer = ...
writer.println("The line");

Use a BufferedWriter and use writer.newLine() after every write-operation that represents one line.

Or, use a PrintWriter and writer.println().

If you are using BufferedWriter then you can use an inbuilt method :

BufferedWriter writer = Files.newBufferedWriter(output, charset);
writer.newLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM