Sam
Sam

Reputation: 6890

Why does Java convert \n\r to \\n\\r when reading them from DB

I have some text in the database(H2) as follows:

--------------------------------------------------------
ID  |       User     |            Properties           |
--------------------------------------------------------
1   |       Oli      |     age=23\n\rgender=MALE\n\r   |
--------------------------------------------------------
2   |       Umpa     |     age=23\n\rjob=STUDENT\n\r   |
--------------------------------------------------------

When I query these rows in my application, Java converts all \n\r characters to \\n\\rand it means there aren't any LF and CR characters in the final string in my application.

Finally, I have replaced \n\r characters by \n\r in the program and the problem was solved. (queried_column.replace("\\n\\r","\r\n"))

Now, my question is why Java has this behavior?

Upvotes: 1

Views: 805

Answers (1)

Max Vollmer
Max Vollmer

Reputation: 8598

Because the text in your database doesn't contain LF or CR characters, it contains \ characters, n characters and r characters. So Java isn't converting anything, it gives you exactly the text from the database.

Your solution to un-escape those special characters is correct.

Upvotes: 1

Related Questions