In this tutorial, You will learn how to remove line breaks from a file in Java. The examples in this tutorial will cover how to use Java IO, Java NIO, and Commons IO.

Create a Maven project

To create a new Maven project, use the following link which will redirect you to an article on the website.

Once you create a new project, copy and paste the following code into the pom.xml file.

  <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.13.0</version>
        </dependency>

Use the keyboard shortcut CTRL+SHIFT+O to reload the Maven changes. This will download the Commons IO dependency and add it to the project’s classpath.

Create text files

Under the root folder of your project, create a file named input-file.txt. Copy and paste the following text into the file.

Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.

This file contains 8 lines of Lorem ipsum text and you will use the file to remove the line breaks in the text.

Create a second file named output-file.txt under the root folder of your project. The result of removing line breaks from the text in the first text file gets written in this file.

Using Java IO

Create a file named UsingJavaIO.java under the package src/main/java/com/javawhizz. Copy and paste the following code into the file.

package com.javawhizz;


import java.io.*;

public class UsingJavaIO {
    public static void main(String[] args) {

        try (BufferedReader bufferedReader = new BufferedReader(
                new FileReader("input-file.txt")
        ); BufferedWriter bufferedWriter = new BufferedWriter(
                new FileWriter("output-file.txt")
        );){

            String fileLine;

            while ((fileLine = bufferedReader.readLine()) != null){
                String line = fileLine.replace("\\r|\\n", "");

                bufferedWriter.write(line);
            }

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

The BufferedReader and BufferedWriter classes come from the Java IO package. In this code, use the try-with-resource to create a single instance of each of the classes.

As a result, the connections to the file will get closed for you instead of doing it yourself.

Next, use a while loop to iterate through the lines by leveraging the readLine() method. As you iterate through the lines, remove the line breaks using the replace() method.

Assign the resulting String to a temporary variable. Next, call the write() method of BufferedWriter and pass the String. This will write the resulting String to the output file as a single line without line breaks.

Output

Lorem ipsum dolor sit amet, consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamcolaboris nisi ut aliquip ex ea commodo consequat. Duis auteirure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sintoccaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum.

Using Java NIO

Create a file named UsingJavaNIO.java under the package src/main/java/com/javawhizz. Copy and paste the following code into the file.

package com.javawhizz;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class UsingJavaNIO {
    public static void main(String[] args) {
        try {
            List<String> fileString = Files
                    .readAllLines(Paths.get("input-file.txt"),
                    StandardCharsets.UTF_8);

            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < fileString.size(); i++) {
                stringBuilder.append(fileString.set(i,
                        fileString.get(i).replaceAll("\\r|\\n", "")));
            }

            Files
                    .writeString(Paths.get("output-file.txt"),
                            stringBuilder.toString());

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

The Java NIO is a package that you can leverage when working with files and directories. The Files class from the package provides various methods to manipulate files.

For example, in this code, use the readAllLines() method to read the lines in the text file. Next, create a new instance of StringBuilder that you will use to construct the new String.

Since the readAllLines() method returns a list of strings, use a for loop to iterate through the list. As you iterate through the list, use the replace() method to remove the line breaks from each line.

At the same time, call the append() method and pass the resulting String. As a result, the StringBuilder will construct a new String without line breaks.

Output

Lorem ipsum dolor sit amet, consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamcolaboris nisi ut aliquip ex ea commodo consequat. Duis auteirure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sintoccaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum.

Using Commons IO

Create a file named UsingCommonsIO.java under the package src/main/java/com/javawhizz. Copy and paste the following code into the file.

package com.javawhizz;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class UsingCommonsIO {
    public static void main(String[] args) {

        try {
            String fileString = FileUtils.readFileToString(new File("input-file.txt"),
                    StandardCharsets.UTF_8);

            String lines = fileString.replaceAll("\\r|\\n", "");

            FileUtils.writeStringToFile(new File("output-file.txt"),
                    lines,
                    StandardCharsets.UTF_8);

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

Note that you added this third-party library at the beginning of the tutorial. This library is very straightforward and easy to understand.

The FileUtils class has a static method named readFileToString(). Call this method and pass the name of the file to read the lines in the file.

Next, call the replaceAll() method of the resulting String to remove the line breaks. The first argument of the method is the regular expression \\r|\\n while the second is an empty String.

As a result, the method will replace all the lines with an empty String and that’s how the line breaks get removed. Next, call the static method writeStringToFile() and pass the arguments as shown above.

As a result, the method will write the resulting String as a single line without line breaks.

Output

Lorem ipsum dolor sit amet, consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamcolaboris nisi ut aliquip ex ea commodo consequat. Duis auteirure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sintoccaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum.

Conclusion

In this tutorial, you have learned how to remove line breaks from a file in Java. Using the Java IO package, Java NIO package, and Commons IO are some of the methods mentioned.

Keep in mind that the inputs for the replace() and replaceAll() methods should be the regular expression "\\r|\\n" and the empty String.

Happy Hacking!


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *