Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (1.4k points)

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?

1 Answer

0 votes
by (13.2k points)

replace() returns a new file with all the changes.It does not make any changes in the original one. So, you will need to use the assignment operator ( = ) to make changes in it.

String text = readFileAsString("textfile.txt");

text = text.replace("\n", "").replace("\r", "");

Related questions

Browse Categories

...