简体   繁体   English

在Java中写入文本文件时插入换行符

[英]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. 学习FileWriter时我略有删除...最终目标是编写一个程序,它将“生成”一个.bat文件,该文件将由启动.jar的批处理代码执行。 The problem is, I have no clue how to make sure that every FileWriter.write(); 问题是,我不知道如何确保每个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类提供了自动为您添加换行符的方法( 编辑:它还将自动为您的操作系统使用正确的换行符):

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

Use a BufferedWriter and use writer.newLine() after every write-operation that represents one line. 使用BufferedWriter并在每次代表一行的写操作后使用writer.newLine()。

Or, use a PrintWriter and writer.println(). 或者,使用PrintWriter和writer.println()。

If you are using BufferedWriter then you can use an inbuilt method : 如果您使用的是BufferedWriter那么您可以使用内置方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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