Has anybody found a way how to specify the Java line.separator
property on VM startup? I was thinking of something like this:
java -Dline.separator="\n"
But this doesn't interprete the "\n" as linefeed character. Any ideas?
Has anybody found a way how to specify the Java line.separator
property on VM startup? I was thinking of something like this:
java -Dline.separator="\n"
But this doesn't interprete the "\n" as linefeed character. Any ideas?
I wouldn't do that if I were you. The line-separator is platform specific, and should remain so. If you want to write windows-only or linux-only files, define a
UNIX_LINE_SEPARATOR
constant somewhere and use it instead.Try using
java -Dline.separator=$'\n'
. That should do the trick, at least in bash.Here is a test-run:
Note:
The expression
$''
uses the Bash feature ANSI-C Quoting. It expands backslash-escaped characters, thus$'\n'
produces a line feed (ASCII code 10) character, enclosed in single quotes. See Bash manual, section 3.1.2.4 ANSI-C Quoting.To bridge the gap between aioobe and Bozho's answers, I also would advise against setting the
line.separator
parameter at JVM startup, as this potentially breaks many fundamental assumptions the JVM and library code makes about the environment being run in. For instance, if a library you depend on relies online.separator
in order to store a config file in a cross-platform way, you've just broken that behavior. Yes, it's an edge case, but that makes it all the more nefarious when, years from now, a problem does crop up, and now all your code is dependent on this tweak being in place, while your libraries are (correctly) assuming it isn't.That said, sometimes these things are out of your control, like when a library relies on
line.separator
and provides no way for you to override that behavior explicitly. In such a case, you're stuck overriding the value, or something more painful like re-implementing or patching the code manually.For those limited cases, the it's acceptable to override
line.separator
, but we've got to follow two rules:Both of these requirements are well served by
AutoCloseable
and the try-with-resources syntax, so I've implemented aPropertiesModifier
class that cleanly provides both.My use case was with
Files.write()
, which is a very convenient method, except it explicitly relies online.separator
. By wrapping the call toFiles.write()
I can cleanly specify the line separator I want to use, without risking exposing this to any other parts of my application (take note of course, that this still isn't thread-safe).