Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default line ending in Java

Tags:

java

newline

lf

eol

I'm working with Java in a multi-platform environment (Windows + Linux). Whatever text files we produce, however, should use LF as their EOL sequence.

Is there a way I can force Java to use this EOL sequence regardless on the platform I'm running a program on? I'd like not to have to change the whole program, i.e. all calls to System.out.println and similar should be kept as is, only the *ln at the end of the function should always output an "0x0A" and never "0x0D 0x0A".

I could think of two different ways of doing that, but I don't know if either one is possible:

  1. override the platform-dependent default EOL sequence
  2. make Java believe I'm running Linux even when I run my program on the DOS command line

Is any of this possible? Or something else perhaps?

like image 761
user1313142 Avatar asked Apr 04 '12 14:04

user1313142


People also ask

What line ending do you use?

Whereas Windows follows the original convention of a carriage return plus a line feed ( CRLF ) for line endings, operating systems like Linux and Mac use only the line feed ( LF ) character. The history of these two control characters dates back to the era of the typewriter.

What Windows line ending?

On Windows, line-endings are terminated with a combination of a carriage return (ASCII 0x0d or \r) and a newline(\n), also referred to as CR/LF. On the Mac Classic (Mac systems using any system prior to Mac OS X), line-endings are terminated with a single carriage return (\r or CR). (Mac OS X uses the UNIX convention.)

What are Unix line endings?

DOS uses carriage return and line feed ("\r\n") as a line ending, which Unix uses just line feed ("\n"). You need to be careful about transferring files between Windows machines and Unix machines to make sure the line endings are translated properly.


2 Answers

You can try setting the corresponding system property like System.setProperty("line.separator", "something you need"); (It can also be achieved throug command-line parameters to JVM)

Or, maybe, you can use print insetad of println and print line-breaking characters ("\r", "\n" or their combination) where you need it.

like image 187
max.shmidov Avatar answered Oct 06 '22 12:10

max.shmidov


Have a look at this and this. If you put those together, you'll find out that System.setProperty("line.separator", "\n"); may solve your problem.

Haven't tested it though, that's why I added the links, so you can check for yourself.

like image 36
gleerman Avatar answered Oct 06 '22 13:10

gleerman