Java 如何制作";%";等于\";

Java 如何制作";%";等于\";,java,string,Java,String,如果在Windows上运行此代码,为什么b不等于true System.setProperty("line.separator", "\n"); String s=String.format("%n"); boolean b="\n".equals(s); 我希望s是“\n”而不是“\r\n”,即使在Windows上也是如此。问题是,行分隔符是在系统类中定义和初始化的 在调用System.setproperty()之前,System类已经初始化,此时lineSeparator被初始化为系统属性

如果在Windows上运行此代码,为什么
b
不等于
true

System.setProperty("line.separator", "\n");
String s=String.format("%n");
boolean b="\n".equals(s);

我希望
s
“\n”
而不是
“\r\n”
,即使在Windows上也是如此。

问题是,
行分隔符
是在
系统
类中定义和初始化的

在调用
System.setproperty()
之前,
System
类已经初始化,此时
lineSeparator
被初始化为系统属性。以后不会更改

您必须在命令行选项上传递系统属性


或者,可以使用反射强制更改
System.lineSeparator
字段。这不能保证有效。

不幸的是,这里唯一的方法是反射:

Field lineSeparator = System.class.getDeclaredField("lineSeparator");

lineSeparator.setAccessible(true);
lineSeparator.set(null, "\n");

@Real怀疑论者,因为我的代码应该在所有平台上产生相同的结果。您应该只使用
\n
而不是
%n
。。。除非代码不在您的控制之下。但是
System.setProperty(“line.separator”,“\n”)Files.write这样的写入方法,则会考虑使用code>。嗯,它可能正在获取当前系统属性;而
String.format
没有。让
String.format
获取当前属性没有希望吗?嗯。我认为Oracle需要更改其文档。这确实是一种误导。事实上,源代码显示
Files.write()
直接使用属性,而
Formatter.format()
使用
System.lineSeparator()
@bayou.io
System.lineSeparator()
记录在案,因此它总是返回与系统属性初始值相同的值。因此,它的工作方式不能改变,因为它会破坏现有的代码。最好的办法是使文档与代码相匹配。