[英]How do i create a line breaker when writing a file in Java?
I'm working on a code that takes in a couple of inputs and re-write them into a .txt file of my creation but to my dismay the output file can not contain a line-breaker even with the appropriate formatting. 我正在处理一个需要几个输入并将它们重新写入到我创建的.txt文件中的代码,但令我沮丧的是,即使使用适当的格式,输出文件也不能包含换行符。 I'm using Formatter(java.util) 我正在使用Formatter(java.util)
public void file(Scanner s, Formatter f){
String s1 = s.nextLine();
if (!"end".equals(s1)){
f.format("%s\n%s", s1, " ");
file(s,f);
}
f.close();
}
public void file(Scanner input,Formatter f,int state){
String s1 = input.nextLine();
int loopStop = 0;
if (state == 1){
file(input, f);
} else {
while (!"end".equals(s1) && loopStop<11){
f.format("%s\n\n%s", s1, " ");
s1 = input.nextLine();
loopStop++;
}
f.close();
}
}
对平台特定的行分隔符使用'%n':
f.format("%s%n%n%s", s1, " ");
Try with System.getProperty("line.separator")
尝试使用System.getProperty("line.separator")
Read it here about System Properties with complete list of System properties. 在此处阅读有关系统属性以及完整的系统属性列表。
The System class maintains a Properties object that describes the configuration of the current working environment. System类维护一个Properties对象,该对象描述当前工作环境的配置。
"line.separator" - Sequence used by operating system to separate lines in text files “ line.separator”-操作系统用于分隔文本文件中的行的序列
Try with System.lineSeparator() as well that states: 尝试使用System.lineSeparator()并指出:
Returns the system-dependent line separator string. 返回系统相关的行分隔符字符串。 It always returns the same value - the initial value of the system property line.separator. 它总是返回相同的值-系统属性line.separator的初始值。
On UNIX systems, it returns "\\n"; 在UNIX系统上,它返回“ \\ n”; on Microsoft Windows systems it returns "\\r\\n". 在Microsoft Windows系统上,它返回“ \\ r \\ n”。
Assuming that you're using Windows, you need to use \\r\\n
which is the proper combination of line-break in Windows or simply use System.getProperty("line.separator");
假设您使用的是Windows,则需要使用\\r\\n
这是Windows中换行符的正确组合),或者只需使用System.getProperty("line.separator");
to get the newline combination. 获得换行组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.