Java Readable Interface

Introduction

The Readable interface in Java is a functional interface that represents a source of characters. It allows reading a sequence of characters into a CharBuffer.

Table of Contents

  1. What is the Readable Interface?
  2. Common Methods
  3. Examples of Using the Readable Interface
  4. Conclusion

1. What is the Readable Interface?

The Readable interface provides a method for reading characters into a CharBuffer. It is implemented by classes like Reader and Scanner.

2. Common Methods

  • read(CharBuffer cb): Reads characters into the specified CharBuffer.

3. Examples of Using the Readable Interface

Example 1: Implementing Readable in a Custom Class

This example demonstrates how to implement the Readable interface in a custom class.

import java.nio.CharBuffer;

public class CustomReadable implements Readable {
    private String data;
    private int currentPosition = 0;

    public CustomReadable(String data) {
        this.data = data;
    }

    @Override
    public int read(CharBuffer cb) {
        if (currentPosition >= data.length()) {
            return -1; // End of input
        }
        cb.append(data.charAt(currentPosition++));
        return 1; // Number of characters read
    }

    public static void main(String[] args) {
        CustomReadable readable = new CustomReadable("Hello, World!");
        CharBuffer buffer = CharBuffer.allocate(50);

        while (readable.read(buffer) != -1) {
            // Continue reading
        }

        buffer.flip();
        System.out.println("Buffer content: " + buffer.toString());
    }
}

Output:

Buffer content: Hello, World!

Example 2: Using Readable with Scanner

This example shows how to use Readable with a Scanner to read from a custom readable source.

import java.nio.CharBuffer;
import java.util.Scanner;

public class ReadableWithScannerExample {
    public static void main(String[] args) {
        Readable readable = CharBuffer.wrap("This is a test.");
        Scanner scanner = new Scanner(readable);

        while (scanner.hasNext()) {
            System.out.println(scanner.next());
        }
        scanner.close();
    }
}

Output:

This
is
a
test.

4. Conclusion

The Readable interface in Java provides a standard way to read character data into a CharBuffer. By implementing this interface, custom classes can be used as character sources in Java applications, allowing for flexible character input handling.

Comments