How to remove line breaks from a file in Java?

How can I replace all line breaks from a string in Java in such a way that will work on Windows and Linux (ie no OS specific problems of carriage return/line feed/new line etc.)?

I’ve tried (note readFileAsString is a function that reads a text file into a String):

String text = readFileAsString("textfile.txt");
text.replace("\n", "");

but this doesn’t seem to work.

How can this be done?

17 Answers
17

Leave a Comment