How to remove line breaks from a file in Java?

JavaStringNewlineLine Breaks

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

You need to set text to the results of text.replace():

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

This is necessary because Strings are immutable -- calling replace doesn't change the original String, it returns a new one that's been changed. If you don't assign the result to text, then that new String is lost and garbage collected.

As for getting the newline String for any environment -- that is available by calling System.getProperty("line.separator").

Solution 2 - Java

As noted in other answers, your code is not working primarily because String.replace(...) does not change the target String. (It can't - Java strings are immutable!) What replace actually does is to create and return a new String object with the characters changed as required. But your code then throws away that String ...


Here are some possible solutions. Which one is most correct depends on what exactly you are trying to do.

// #1
text = text.replace("\n", "");

Simply removes all the newline characters. This does not cope with Windows or Mac line terminations.

// #2
text = text.replace(System.getProperty("line.separator"), "");

Removes all line terminators for the current platform. This does not cope with the case where you are trying to process (for example) a UNIX file on Windows, or vice versa.

// #3
text = text.replaceAll("\\r|\\n", "");

Removes all Windows, UNIX or Mac line terminators. However, if the input file is text, this will concatenate words; e.g.

Goodbye cruel
world.

becomes

Goodbye cruelworld.

So you might actually want to do this:

// #4
text = text.replaceAll("\\r\\n|\\r|\\n", " ");

which replaces each line terminator with a space1. Since Java 8 you can also do this:

// #5
text = text.replaceAll("\\R", " ");

And if you want to replace multiple line terminator with one space:

// #6
text = text.replaceAll("\\R+", " ");

1 - Note there is a subtle difference between #3 and #4. The sequence \r\n represents a single (Windows) line terminator, so we need to be careful not to replace it with two spaces.

Solution 3 - Java

This function normalizes down all whitespace, including line breaks, to single spaces. Not exactly what the original question asked for, but likely to do exactly what is needed in many cases:

import org.apache.commons.lang3.StringUtils;

final String cleansedString = StringUtils.normalizeSpace(rawString);

Solution 4 - Java

If you want to remove only line terminators that are valid on the current OS, you could do this:

text = text.replaceAll(System.getProperty("line.separator"), "");

If you want to make sure you remove any line separators, you can do it like this:

text = text.replaceAll("\\r|\\n", "");

Or, slightly more verbose, but less regexy:

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

Solution 5 - Java

This would be efficient I guess

String s;
s = "try this\n try me.";
s.replaceAll("[\\r\\n]+", "")

Solution 6 - Java

str = str.replaceAll("\\r\\n|\\r|\\n", " ");

Worked perfectly for me after searching a lot, having failed with every other line.

Solution 7 - Java

Linebreaks are not the same under windows/linux/mac. You should use System.getProperties with the attribute line.separator.

Solution 8 - Java

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)

Solution 9 - Java

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

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

Solution 10 - Java

You may want to read your file with a BufferedReader. This class can break input into individual lines, which you can assemble at will. The way BufferedReader operates recognizes line ending conventions of the Linux, Windows and MacOS worlds automatically, regardless of the current platform.

Hence:

BufferedReader br = new BufferedReader(
    new InputStreamReader("textfile.txt"));
StringBuilder sb = new StringBuilder();
for (;;) {
    String line = br.readLine();
    if (line == null)
        break;
    sb.append(line);
    sb.append(' ');   // SEE BELOW
}
String text = sb.toString();

Note that readLine() does not include the line terminator in the returned string. The code above appends a space to avoid gluing together the last word of a line and the first word of the next line.

Solution 11 - Java

In Kotlin, and also since Java 11, String has lines() method, which returns list of lines in the multi-line string. You can get all the lines and then merge them into a single string.

With Kotlin it will be as simple as

str.lines().joinToString("")

Solution 12 - Java

I find it odd that (Apache) StringUtils wasn't covered here yet.

you can remove all newlines (or any other occurences of a substring for that matter) from a string using the .replace method

StringUtils.replace(myString, "\n", "");

This line will replace all newlines with the empty string.

because newline is technically a character you can optionally use the .replaceChars method that will replace characters

StringUtils.replaceChars(myString, '\n', '');

Solution 13 - Java

You can use apache commons IOUtils to iterate through the line and append each line to StringBuilder. And don't forget to close the InputStream

StringBuilder sb = new StringBuilder();
FileInputStream fin=new FileInputStream("textfile.txt");
LineIterator lt=IOUtils.lineIterator(fin, "utf-8");
while(lt.hasNext())
{
  sb.append(lt.nextLine());
}
String text = sb.toString();
IOUtils.closeQuitely(fin);

Solution 14 - Java

FYI if you can want to replace simultaneous muti-linebreaks with single line break then you can use

myString.trim().replaceAll("[\n]{2,}", "\n")

Or replace with a single space

myString.trim().replaceAll("[\n]{2,}", " ")

Solution 15 - Java

You can use generic methods to replace any char with any char.

public static void removeWithAnyChar(String str, char replceChar,
		char replaceWith) {
	char chrs[] = str.toCharArray();
	int i = 0;
	while (i < chrs.length) {

		if (chrs[i] == replceChar) {
			chrs[i] = replaceWith;
		}
		i++;
	}
	
}

Solution 16 - Java

org.apache.commons.lang.StringUtils#chopNewline

Solution 17 - Java

Try doing this:

 textValue= textValue.replaceAll("\n", "");
 textValue= textValue.replaceAll("\t", "");
 textValue= textValue.replaceAll("\\n", "");
 textValue= textValue.replaceAll("\\t", "");
 textValue= textValue.replaceAll("\r", "");
 textValue= textValue.replaceAll("\\r", "");
 textValue= textValue.replaceAll("\r\n", "");
 textValue= textValue.replaceAll("\\r\\n", "");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontree-hackerView Question on Stackoverflow
Solution 1 - JavaKaleb BraseeView Answer on Stackoverflow
Solution 2 - JavaStephen CView Answer on Stackoverflow
Solution 3 - JavaDavid McWhorterView Answer on Stackoverflow
Solution 4 - JavaFabian SteegView Answer on Stackoverflow
Solution 5 - JavaJSBachView Answer on Stackoverflow
Solution 6 - JavaRenán DView Answer on Stackoverflow
Solution 7 - JavaAifView Answer on Stackoverflow
Solution 8 - JavaMukeshKoshyMView Answer on Stackoverflow
Solution 9 - JavaViktor KlangView Answer on Stackoverflow
Solution 10 - JavaThomas PorninView Answer on Stackoverflow
Solution 11 - JavaAbstractVoidView Answer on Stackoverflow
Solution 12 - JavasvarogView Answer on Stackoverflow
Solution 13 - JavaShravan RamamurthyView Answer on Stackoverflow
Solution 14 - JavaSourav ChandraView Answer on Stackoverflow
Solution 15 - JavaRakesh ChaudhariView Answer on Stackoverflow
Solution 16 - JavaKumar AbhishekView Answer on Stackoverflow
Solution 17 - JavaseyfView Answer on Stackoverflow