Sunday 12 January 2020

Remove line breaks from a file


Line break is a control character, used to signify the end of a line of text and the start of a new one. Line break characters are depend on operating system.

Following table summarizes the line break characters in different operating systems.

Operating System
Abbreviation
Escape Sequence
Linux
LF
\n
Windows
CR LF
\r\n
IBM Mainframe
NL
\025

Following snippet replace line breaks with an empty space.

String data = readFileAsString(filePath);
data = data.replace("\r\n", " ").replace("\n", " ");

logfile.txt
VM memory consumption exceeded 85%
CPU usage exceed 98%
Total failures 123


App.java
package com.sample.app;

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

public class App {

 public static String readFileAsString(String filePath) throws IOException {
  if (filePath == null || filePath.isEmpty()) {
   return null;
  }

  return new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
 }

 public static void main(String args[]) throws IOException {
  String filePath = "logfile.txt";
  String data = readFileAsString(filePath);
  data = data.replace("\r\n", " ").replace("\n", " ");
  System.out.println(data);
 }

}

Run App.java, you will see below messages in console.


VM memory consumption exceeded 85% CPU usage exceed 98% Total failures 123


You may like

No comments:

Post a Comment