Handling newline in input between Windows and Linux

I think this is a standard problem, which may have been asked before, but I could not get an exact answer, so I'm sending a question.

The problem is that our server is running in a Linux window. We access the server through a browser in the window window to enter data in a field that should contain several lines that the user can enter by pressing the enter key after each line the alphabet GC Protection

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

I had three questions.

  • Input contains "\ r \ n" or "\ n"

  • If the input contains "\ r \ n", the linux line.separator property (vm property) will not work for me, as it says "\ n" and therefore can leave "\ r" in the data.

  • If "\ r" is left in the data, if I open the file on a Windows machine, does that mean a newline?

Finally, can anyone tell me a standard way to deal with this problem?

+5
source share
5 answers

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

Therefore, if you have not remade something in linux, it should appear in \n.

You can re-select \r\nand \nreplace whatever you want to avoid problem 3.

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

+3

java.io.DataInputStream java.io.BufferedInputReader readLine(). DataInputStream , , readLine() .

java.io.PrintWriter, printLn() , . java.io.BufferedWriter public newLine().

+3

, , , - .

StringBuilder sb=new StringBuilder();
// append your texts here and to go to a new line use
    if(System.getProperty("os.name").startsWith("Windows")){

                sb.insert("\r\n");
            }
            else {
            sb.insert("\n");
    }

, - , , , , Linux.

+1

, ?

String[] lines = inputString.split("\r?\n");

The syntax is not 100% certain, but the main idea of ​​the regular expression is “zero or one,” and exactly one \ n ". Or, if you just want to normalize the input:

inputString = inputString.replace("\r?\n", "\n");

It’s not very painful .; -)

0
source

Thanks for the answer guys. Finally, looking at the proposal made by Kevin, we used StringReader and BufferedReader to overcome this problem. We used a string reader because the data is read as a string from a query.

Hope this question helps people in the future.

-1
source

All Articles