How to remove line breaks from a file in Java?
There are several ways to remove line breaks from a file in Java. Here are two options:
- Read the file into a string and use a regular expression to replace line breaks with an empty string:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) throws IOException {
String fileContent = new String(Files.readAllBytes(Paths.get("file.txt")));
String noLineBreaks = fileContent.replaceAll(Pattern.quote(System.getProperty("line.separator")), "");
System.out.println(noLineBreaks);
}
}
- Read the file line by line and append the lines to a string, omitting the line breaks:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
String noLineBreaks = sb.toString();
System.out.println(noLineBreaks);
}
}
Both of these options will read the contents of the file "file.txt" and print the contents to the console with all line breaks removed.