eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

Sometimes, we need to read raw text from files and clean up messy content by removing line breaks.

In this tutorial, we’ll explore various approaches for removing line breaks from files in Java.

2. A Word About Line Breaks

Before we dive into the code for reading from files and removing line breaks, let’s quickly understand the target objects we want to remove: the line breaks.

At first glance, it’s pretty straightforward. A line break is a character breaking a line. However, there are different kinds of line breaks. We may fall into pitfalls if we don’t treat them properly. An example can explain it quickly.

Let’s say we have two text files, mutiple-line-1.txt and multiple-line-2.txt. Let’s call them file1 and file2. If we open them in IDE’s editor, for example, IntelliJ, both files look the same:

A,
 B,
 C,
 D,
 E,
 F

As we can see, each file has six lines, and there is a leading space character on each line from the second line. So, we believe file1 and file2 contain the exact text.

However, now let’s print the file content using the cat command with the -n (show line numbers) and -e (show non-printing characters) options:

$ cat -ne multiple-line-1.txt
     1  A,$
     2   B,$
     3   C,$
     4   D,$
     5   E,$
     6   F$

file1’s output is the same as we saw in the IntelliJ editor. But file2 looks quite different:

$ cat -ne multiple-line-2.txt
     1  A,^M B,$
     2   C,$
     3   D,^M E,$
     4   F$

This is because there are three different line breaks:

  • ‘\r’ – CR (Carriage Return), the line break in Mac OS before X
  • ‘\n’ – LF (Line Feed), the line break in *nix and Mac OS
  • ‘\r\n’ – CRLF, the line break in Windows

cat -e displays CRLF as ‘^M‘. So, we see file2 contains CRLF. Possibly, the file is created in Windows. Depending on requirements, we may want to remove all kinds of line breaks or only line breaks of the current system.

Next, we’ll take these two files as examples to see how to read content from them and remove line breaks. For simplicity, we’ll create two helper methods to return each file’s Path:

Path file1Path() throws Exception {
    return Paths.get(this.getClass().getClassLoader().getResource("multiple-line-1.txt").toURI());
} 

Path file2Path() throws Exception {
    return Paths.get(this.getClass().getClassLoader().getResource("multiple-line-2.txt").toURI());
}

Note that the approaches used in this article require reading the whole text into memory, so be aware of very large files.

3. Replacing line.separator With an Empty String

The system property line.separator stores the line separator that is specific to the current operating system. Therefore, if we only want to remove line breaks particular to the current system, we can replace line.separator with an empty string. For example, this approach removes all line breaks from file1 on a Linux box:

String content = Files.readString(file1Path(), StandardCharsets.UTF_8);

String result = content.replace(System.getProperty("line.separator"), "");
assertEquals("A, B, C, D, E, F", result);

We use the Files class’s readString() method to load file content in a string. Then, we apply the replacement by replace().

However, the same approach won’t remove all line breaks from file2, as it contains CRLF line breaks:

String content = Files.readString(file2Path(), StandardCharsets.UTF_8);

String result = content.replace(System.getProperty("line.separator"), "");
assertNotEquals("A, B, C, D, E, F", result); // <-- NOT equals assertion!

Next, let’s see if we can remove all line breaks system-independently.

4. Replacing “\n” and “\r” With Empty Strings

We’ve learned all three different line breaks cover “\n” and “\r” characters. Therefore, if we want to remove all line breaks system-independently, we can replace “\n” and “\r” with empty strings:

String content1 = Files.readString(file1Path(), StandardCharsets.UTF_8);

// file contains CRLF
String content2 = Files.readString(file2Path(), StandardCharsets.UTF_8);

String result1 = content1.replace("\r", "").replace("\n", "");
String result2 = content2.replace("\r", "").replace("\n", "");

assertEquals("A, B, C, D, E, F", result1);
assertEquals("A, B, C, D, E, F", result2);

Of course, we can also use the regex-based replaceAll() method to achieve the same goal. Let’s take file2 as an example to see how it works:

String resultReplaceAll = content2.replaceAll("[\\n\\r]", "");
assertEquals("A, B, C, D, E, F", resultReplaceAll);

5. Using readAllLines() and Then join()

Let’s recall the two approaches we’ve learned so far. We first read the entire content from a file, then replace the line.separator system property or “\n” and “\r” characters with empty. One commonality between these approaches is that we manually manage the line breaks ourselves.

The Files class offers readAllLines() to read the file content into lines and return a list of strings. It’s worth noting that readAllLines() takes all mentioned three line breaks as a line separator. In other words, this method removes all line breaks from the input. What we need to do is join the elements in the returned list.

The join() method is pretty convenient to join a list or an array of strings:

List<String> lines1 = Files.readAllLines(file1Path(), StandardCharsets.UTF_8);

// file contains CRLF
List<String> lines2 = Files.readAllLines(file2Path(), StandardCharsets.UTF_8);

String result1 = String.join("", lines1);
String result2 = String.join("", lines2);

assertEquals("A, B, C, D, E, F", result1);
assertEquals("A, B, C, D, E, F", result2);

6. Conclusion

In this article, we first discussed the different kinds of line breaks. Then, we explored various approaches to removing line breaks from a file.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments