Java 记事本无法识别 \n 字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9701438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
notepad doesn't recognize \n character?
提问by dhananjay
I am copying some css classes to one file. Classes get copied very well, but I have a problem that when I am trying to open it using notepad it gives one square instead of \n
character. It opens well in Edit+. Here is my code:
我正在将一些 css 类复制到一个文件中。类被复制得很好,但我有一个问题,当我尝试使用记事本打开它时,它会给出一个正方形而不是\n
字符。它在 Edit+ 中打开得很好。这是我的代码:
String fileName = new File(oldFileName).getName();
BufferedWriter out = null;
FileWriter fw = new FileWriter("D:\temp\UPDATED_"+fileName);
out = new BufferedWriter(fw);
for (CSSStyleRule p : finlist.values()) {
String t = null;
String m = p.toString();
if (m.charAt(0) == '*') {
t = m.substring(1);
} else {
t = m;
}
String main = format(t);
out.write(main);
out.write("\n");
}
also see this format() function
另请参阅此 format() 函数
private static String format(String input) {
int s = input.indexOf('{');
int p = input.indexOf('}');
int w = input.indexOf(';');
if(w==-1)
{
w=p-1;
String []part=input.split("}");
input= part[0].concat(";").concat("}");
}
String m = input.substring(0, s).trim().concat("{\n")
.concat(input.substring(s + 1, w + 1).trim())
.concat(input.substring(w + 1, p));
String a[] = m.split(";");
String main = "";
for (String part : a) {
if (part.contains("rgb")) {
part = convert(part);
}
if(part.contains("FONT-FAMILY") || part.contains("font-family")){
part=process(part);
}
main = main.concat(part.trim().concat(";")).concat("\n");
}
main = main.concat("}");
return main;
}
How to make it show up properly in notepad?
如何让它在记事本中正确显示?
采纳答案by MByD
Windows uses \r\n
for new line. Use the line.separator
property instead:
Windows 用于\r\n
换行。改用该line.separator
属性:
public static String newLine = System.getProperty("line.separator");
//...
out.write(newLine);
回答by hmjd
Use System.getProperty("line.separator");
, not hardcoded "\n"
, as line separator on windows is "\r\n"
or, in this case, use BufferedWriter
's newLine()
method:
使用System.getProperty("line.separator");
,而不是硬编码"\n"
,作为 Windows 上的行分隔符,"\r\n"
或者,在这种情况下,使用BufferedWriter
的newLine()
方法:
out.write(main);
out.newLine();