[英]Java: how to write formatted output to plain text file
我正在开发一个小型的java应用程序。 在某些时候,我在一个纯文本文件中写一些数据。 使用以下代码:
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();
现在一切顺利,文件是用预期的文本创建的。 唯一的问题是文本没有格式化所有文本都在单行上。 但是,如果我在MS Word中复制并粘贴文本,则文本会自动格式化。
有没有办法在纯文本文件中保留文本格式?
注意:通过文本格式我只指\\n
和\\t
将System.getProperty("line.separator")
用于新行 - 这是获取新行分隔符的独立于平台的方式。 (在windows上它是\\r\\n
,在linux上它是\\n
)
此外,如果要在非Windows机器上运行,请避免使用\\t
- 使用X(四个)空格。
您可以使用line.separator
系统属性来解决您的问题。
例如
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
系统属性是一种独立于平台的方法,可以从您的环境中获取换行符。
PrintWriter
独立于此平台 - 使用println()
方法。
您必须使用Java实用程序Formatter ,它可以在这里找到: java.util.Formatter
然后你要做的就是创建一个Formatter
类型的对象,如下所示:
private Formatter output;
在这种情况下, output
将是您要写入的输出文件。
然后你必须将文件名传递给输出对象,如下所示:
output = new Formatter("name.of.your.file.txt")
完成后,您可以使用output.format
命令将文件内容硬编码到输出文件, output.format
命令类似于System.out.println
或printf
命令。
或者使用Scanner
实用程序将数据输入到内存中,然后使用output.format
将此数据输出到输出对象或文件。
这是关于如何将记录写入输出的示例:
output.format( "%d %s %s %2f\n" , field1.decimal, field2.string, field3.string, field4.double)
还有一点比这更多,但这肯定比解析数据或使用一堆复杂的第三方插件更好。
要读取此文件,您可以重定向Scanner实用程序以读取文件而不是控制台:
input = new Scanner(new File( "name.of.your.file.txt")
Windows预计新行和回车符号表示新行。 所以你想要\\ r \\ n使它工作。
Window的记事本需要\\r\\n
才能正确显示换行符。 只有\\n
被记事本忽略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.