Alex Rivera | Logout

How to remove line breaks from a file in Java?

Asked 2010-01-29T15:44:51.617
317

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?

Edit
Report

2 Answers

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

Even though the definition of trim() in oracle website is "Returns a copy of the string, with leading and trailing whitespace omitted."

the documentation omits to say that new line characters (leading and trailing) will also be removed.

In short String text = readFileAsString("textfile.txt").trim(); will also work for you. (Checked with Java 6)

answered 2012-08-31T04:27:34.647
3
String text = readFileAsString("textfile.txt").replace("\n","");

.replace returns a new string, strings in Java are Immutable.

answered 2010-01-29T15:49:26.447

Your Answer