How do I clear a buffer using compact() method?

If you want to clear a buffer, but you want to keep the unread data in the buffer then you need to use the compact() method of the buffer. The compact() method will copy the unread data to the beginning of the buffer and set the position right after the unread data. The limit itself still have the value equals to the buffer capacity. The buffer will be ready to be written again without overwriting the unread data.

package org.kodejava.io;

import java.nio.CharBuffer;

public class BufferCompact {
    public static void main(String[] args) throws Exception {
        CharBuffer buffer = CharBuffer.allocate(64);
        buffer.put("Let's write some Java code! ");

        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());

        // Read 10 chars from the buffer.
        buffer.flip();
        for (int i = 0; i < 10; i++) {
            System.out.print(buffer.get());
        }
        System.out.println();

        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());

        // clear the buffer using compact() method.
        buffer.compact();
        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());

        // Write and read some more data.
        buffer.put("Add some more data.");

        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.print(buffer.get());
        }
    }
}

The output of the code snippet above is:

Position: 28
Limit   : 64
Let's writ
Position: 10
Limit   : 28
Position: 18
Limit   : 64
e some Java code! Add some more data.

How do I reread the content of a buffer?

The example shown below tells you how to reread the contents of a buffer. To reread the data from a buffer we can use the buffer’s rewind() method. This method set the position back to 0 while the limit is unchanged, it still holds the value of how many data can be read from the buffer.

package org.kodejava.io;

import java.nio.CharBuffer;

public class BufferRewind {
    public static void main(String[] args) {
        CharBuffer buffer = CharBuffer.allocate(1024);
        buffer.put("The quick brown fox jumps over the lazy dog.");
        buffer.flip();

        // Read buffer's data using the get() method call.
        while (buffer.hasRemaining()) {
            System.out.print(buffer.get());
        }
        System.out.println();

        // Rewind the buffer will set the position back to 0.
        // We rewind the buffer so that we can reread the buffer
        // data for another purposes.
        buffer.rewind();

        // Reread the buffer and append its data to a StringBuilder
        StringBuilder bufferText = new StringBuilder();
        while (buffer.hasRemaining()) {
            bufferText.append(buffer.get());
        }
        System.out.println(bufferText);
    }
}

The output of the code snippet:

The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.

How do I change the buffer mode between write and read?

A buffer can be read or written. To change the mode between the write mode and read mode we use the flip() method call on the buffer.

There are few things that you should know when you change between the write mode to the read mode. A buffer have the capacity, position and limit properties. The capacity will always be the same on write or read mode. But the position and limit will store different information in each mode.

In write mode the limit will be equals to the capacity, but in read mode the limit will be equals to the last position where the last data were written. The position on the write mode point where the data will be written in the buffer. When calling the flip() method the position will be set to 0 and the limit will be set to the last value of the position.

package org.kodejava.io;

import java.nio.CharBuffer;

public class BufferFlip {
    public static void main(String[] args) {
        CharBuffer buffer = CharBuffer.allocate(1024);
        System.out.println("capacity = " + buffer.capacity());
        System.out.println("position = " + buffer.position());
        System.out.println("limit    = " + buffer.limit());

        buffer.put("Java NIO Programming");

        System.out.println("capacity = " + buffer.capacity());
        System.out.println("position = " + buffer.position());
        System.out.println("limit    = " + buffer.limit());

        buffer.flip();
        System.out.println("capacity = " + buffer.capacity());
        System.out.println("position = " + buffer.position());
        System.out.println("limit    = " + buffer.limit());
    }
}

The program will print the following result:

capacity = 1024
position = 0
limit    = 1024
capacity = 1024
position = 20
limit    = 1024
capacity = 1024
position = 0
limit    = 20

How do I detect non-ASCII characters in string?

The code below detect if a given string has a non ASCII characters in it. We use the CharsetDecoder class from the java.nio package to decode string to be a valid US-ASCII charset.

package org.kodejava.io;

import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharacterCodingException;
import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class NonAsciiValidation {
    public static void main(String[] args) {
        // This string contains a non ASCII character which will produce exception
        // in this program. While the second string has a valid ASCII only characters.
        byte[] invalidBytes = "Copyright © 2021 Kode Java Org".getBytes();
        byte[] validBytes = "Copyright (c) 2021 Kode Java Org".getBytes();

        // Returns a charset object for the named charset.
        CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder();
        try {
            CharBuffer buffer = decoder.decode(ByteBuffer.wrap(validBytes));
            System.out.println(Arrays.toString(buffer.array()));

            buffer = decoder.decode(ByteBuffer.wrap(invalidBytes));
            System.out.println(Arrays.toString(buffer.array()));
        } catch (CharacterCodingException e) {
            System.err.println("The information contains a non ASCII character(s).");
            e.printStackTrace();
        }
    }
}

Below is the result of the program:

[C, o, p, y, r, i, g, h, t,  , (, c, ),  , 2, 0, 2, 1,  , K, o, d, e,  , J, a, v, a,  , O, r, g]
The information contains a non ASCII character(s).
java.nio.charset.MalformedInputException: Input length = 1
    at java.base/java.nio.charset.CoderResult.throwException(CoderResult.java:274)
    at java.base/java.nio.charset.CharsetDecoder.decode(CharsetDecoder.java:820)
    at org.kodejava.io.NonAsciiValidation.main(NonAsciiValidation.java:23)