为什么 和 (String)System.getProperty("line.separator");行为不同? [英] Why does and (String)System.getProperty("line.separator"); act differently?
问题描述
我的程序接受一个文本文件的输入,其中每个单词都由换行符分隔,我的程序接受它并处理数据,然后我需要输出到一个新文件,同时保持控制台输出.>
现在我想知道为什么当我将 " " 附加到我的 stringBuilder 时,它会打印出来,因为它在控制台中有一个新行,但在文件输出中,它不会将它作为一个新行line 并将所有单词放在一行中.
当我使用 newLine 时,它只会在我的控制台输出和我的输出文件中给出一个新行.这是为什么?(String)System.getProperty("line.separator") 是什么导致了这种情况?
String newLine = (String)System.getProperty("line.separator");尝试{BufferedReader fileIn = new BufferedReader(new FileReader(fileName));stringBuilder.append(newLine);while((s = fileIn.readLine()) != null){stringBuilder.append(s);stringBuilder.append(newLine);//使用newLine,}String a = stringBuilder.toString();if(s== null){fileIn.close();}
因为在某些系统 (Linux/Unix) 上,新行被定义为
而在其他系统 (Windows) 上它是 <代码>
代码>.根据阅读文本的软件,它可能会选择坚持这一点,或者更加宽容"地识别甚至
单独识别.
相关维基百科文本(https://en.wikipedia.org/wiki/Newline):
<块引用>基于 ASCII 或兼容字符集的系统使用 LF(换行,' ',0x0A,十进制的 10)或 CR(回车,' ',0x0D,十进制 13)单独,或 CR 后跟 LF(CR+LF,' ', 0x0D0A)
这也是为什么您可以像以前那样从 System
类中检索系统定义的行分隔符,而不是例如将它作为 String中的某个常量代码>类.
My program takes a input of a text file that has words each separated by a newline and my program takes it and deals with the data, and then I am required to output to a new file whilst keeping the console output.
Now I am wondering why when I append " " to my stringBuilder that it prints it out as it were to have a new line in the console, but in the file output, it doesn't take it as a new line and just puts all the words in one line.
When I use newLine, then only does it give a new line in both my console output and my output file. Why is that? What does (String)System.getProperty("line.separator") do that causes this?
String newLine = (String)System.getProperty("line.separator");
try{
BufferedReader fileIn = new BufferedReader(new FileReader(fileName));
stringBuilder.append(newLine);
while((s = fileIn.readLine()) != null){
stringBuilder.append(s);
stringBuilder.append(newLine);//using newLine,
}
String a = stringBuilder.toString();
if(s== null){
fileIn.close();
}
Because on some systems (Linux/Unix) a new line is defined as
while on others (Windows) it is
. Depending on the software reading the text, it may chose to adhere to this or be more "forgiving" recognizing either or even
individually.
Relevant Wikipedia text (https://en.wikipedia.org/wiki/Newline):
Systems based on ASCII or a compatible character set use either LF (Line feed, ' ', 0x0A, 10 in decimal) or CR (Carriage return, ' ', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, ' ', 0x0D0A)
This is also why you can retrieve the system-defined line separater from the System
class as you did, instead of, for example, having it be some constant in the String
class.
这篇关于为什么 和 (String)System.getProperty("line.separator");行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!