Core Java

Remove All Occurrences Of Newline From byte Array

Introduction:

In this article, we’ll uncover ways in which we can remove all line breaks or newline characters from a byte array in Java.

For this tutorial, we are assuming line breaks for our system would mean “\n” character(usually true for a Unix environment).

Removing Line-Breaks from byte Array:

1. Using java.lang.String:

An easy implementation of removing all line breaks from a byte array would involve:

  • Forming a String from a given byte array
  • Further, using a String replaceAll() method to replace all occurrences of “\n” to “”
  • Retrieve the byte[] array using getBytes() method

The code would look something like:

byte[] removeAllNewLineCharacters(byte[] input) {
    String str = new String(input);
    str = str.replaceAll("\n", "");
    return str.getBytes();
}
2. Apache Commons ArrayUtils:

Apache Commons Lang provides ArrayUtils class which can help us remove all occurrences of some specific character from an array.

Why would we ever need it, when we can work our way with String?

The answer is sometimes we have a pretty large-sized array. For such cases, converting it to a String and doing a regex replacement of “\n” would not be very efficient.

Using ArrayUtils.removeAllOccurrences() method will do the job for us quite efficiently:

byte[] removeAllNewLineCharacters(byte[] input) {
    return ArrayUtils.removeAllOccurrences(input, '\n');
}

Conclusion:

In this quick tutorial, we looked at ways in which we can remove all newline characters from a byte array in Java.

Be the First to comment.

Leave a Comment

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