Intellipaat 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?

3 Answers

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", "");

0 votes
by (1.8k points)
We can remove a line break from a file in java but for that we have to read the file line by line and then we have to concatenate the lines and finally we can give the result into a new file.

Steps to remove a line break from a file:

Read the file line by line.
Append each line to a StringBuilder by omitting the line breaks
Now we can write the concatenated string to a new file.
0 votes
by (1.8k points)

We can remove a line break from a file in java but for that we have to read the file line by line and then we have to concatenate the lines and finally we can give the result into a new file.


Steps to remove a line break from a file:

  • Read the file line by line.
  • Append each line to a StringBuilder by omitting the line breaks
  • Now we can write the concatenated string to a new file.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...