Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling newline character in input between Windows and Linux

Tags:

java

I think this is a standard problem which may have been asked before but I could not get the exact answer so posting the issue.

The issue is that our server is running on a linux box. We access the server over the browser on a window box to enter data into field which is supposed to contain multiple lines which user can enter by pressing the enter key after each line Abc Def GHI

When this input field (this is a text area),is read on the linux machine, we want to split the data based on new line character.

I had three question on this.

  1. Does the incoming data contain "\r\n" or "\n"

  2. If incoming data does contain "\r\n", the linux line.separator property (vm property) would not work for me as it would say "\n" and therefore may leave "\r" in the data.

  3. If "\r" is left in the data, if I open the file on a windows machine, will this mean a newline character?

Finally can anyone tell me the standard way to deal with this issue?

like image 545
Fazal Avatar asked Mar 09 '10 00:03

Fazal


2 Answers

The standard java.io.DataInputStream and java.io.BufferedInputReader both handle this automatically through the readLine() method. You really should not use DataInputStream for this since it does not support character sets correctly and it's readLine() has been deprecated for a long time.

For text output, you can use java.io.PrintWriter in which it's printLn(), and related methods with parameters, output the correct newline sequence for the current platform. java.io.BufferedWriter also handles this correctly and provides a public newLine() method.

like image 181
Kevin Brock Avatar answered Oct 01 '22 05:10

Kevin Brock


Linux uses \n.
Windows uses \r\n.

Therefore, unless you've tweaked something in linux, it should be coming in \n.

You could regex out \r\n and \n and replace with whatever you want to avoid problem 3.

http://en.wikipedia.org/wiki/Newline

like image 38
Moki Avatar answered Oct 01 '22 06:10

Moki