Why isn't b
equal to true
if you run this code on Windows?
如果在Windows上运行此代码,为什么b不等于true?
System.setProperty("line.separator", "\n");
String s=String.format("%n");
boolean b="\n".equals(s);
I want s
to be "\n"
and not "\r\n"
, even on Windows.
即使在Windows上,我希望s为“\ n”而不是“\ r \ n”。
2 个解决方案
#1
Unfortunately, the only way here is reflection:
不幸的是,这里唯一的方法是反思:
Field lineSeparator = System.class.getDeclaredField("lineSeparator");
lineSeparator.setAccessible(true);
lineSeparator.set(null, "\n");
#2
The problem is, lineSeparator
is defined and initialized in System
class.
问题是,lineSeparator是在System类中定义和初始化的。
Before you call System.setPropety()
, the System
class is already initalized, and the lineSeparator
is initialized to the system property at that moment. It won't be changed later.
在调用System.setPropety()之前,System类已经初始化,并且lineSeparator在那时被初始化为系统属性。以后不会改变。
You'll have to pass the system property on command line option...
你必须在命令行选项上传递系统属性...
Or, it might be possible to use reflection to forcefully change the System.lineSeparator
field. This is not guaranteed to work.
或者,可以使用反射来强制更改System.lineSeparator字段。这不保证有效。
#1
Unfortunately, the only way here is reflection:
不幸的是,这里唯一的方法是反思:
Field lineSeparator = System.class.getDeclaredField("lineSeparator");
lineSeparator.setAccessible(true);
lineSeparator.set(null, "\n");
#2
The problem is, lineSeparator
is defined and initialized in System
class.
问题是,lineSeparator是在System类中定义和初始化的。
Before you call System.setPropety()
, the System
class is already initalized, and the lineSeparator
is initialized to the system property at that moment. It won't be changed later.
在调用System.setPropety()之前,System类已经初始化,并且lineSeparator在那时被初始化为系统属性。以后不会改变。
You'll have to pass the system property on command line option...
你必须在命令行选项上传递系统属性...
Or, it might be possible to use reflection to forcefully change the System.lineSeparator
field. This is not guaranteed to work.
或者,可以使用反射来强制更改System.lineSeparator字段。这不保证有效。