java 怎么在控制台把换行符打印出来?
在windows环境下
public static void main(String[] args) { String b = String.format("The data download task succeed. %nName:%s ", "1");
System.out.println(b);
String a = "The data download task succeed. \r\n" +
"Name:1 ";
System.out.println(a);
System.out.println(a.equals(b));
}
运行结果为
The data download task succeed. Name:1
The data download task succeed.
Name:1
true
有没有方式可以在控制台不格式化显示,而把原样的换行符打印出来,类似下面这样
The data download task succeed. \r\n Name:1
回答:
public static void main(String[] args) { String b = String.format("The data download task succeed. %nName:%s ", "1");
printWithEscapeSequences(b);
String a = "The data download task succeed. \r\n" +
"Name:1 ";
printWithEscapeSequences(a);
System.out.println(a.equals(b));
}
public static void printWithEscapeSequences(String str) {
String replaced = str.replace("\r", "\\r").replace("\n", "\\n");
System.out.println(replaced);
}
回答:
不改代码就只能替换System.out
了,java io 的 api 都可以这么套娃操作(装饰器模式)
public static void main(String[] args) { String testText = "xxx\r\n";
System.out.println(testText);
// 获取当前的 out
PrintStream oldOut = System.out;
// 在当前的 out 上包装一层,将输出内容里的特殊字符进行替换
PrintStream newOut = new PrintStream(oldOut) {
@Override
public void println(String x) {
String s = x;
if (s != null) {
s = s.replaceAll("\n", "\\\\n");
s = s.replaceAll("\r", "\\\\r");
}
super.println(s);
}
};
// 设置新 out
System.setOut(newOut);
System.out.println(testText);
}
回答:
转义'\'
String a = "The data download task succeed. \\r\\n" + "Name:1 ";
回答:
通过控制台打印来看分割符是不可靠的。可以直接通过System.lineSeparator()来获取当前操作系统的换行符,然后在代码里针对不同操作系统进行特定的处理。
以上是 java 怎么在控制台把换行符打印出来? 的全部内容, 来源链接: utcz.com/p/945383.html