Readable 接口位于 java.lang 包中。它主要用于定义一个可以被读取的对象。
该接口是一个字符输入流相关的接口,用于表示能够提供字符序列以便读取的源。它为字符输入操作提供了一种抽象,使得不同类型的字符源(如文件、网络连接、字符串缓冲区等)可以以统一的方式被读取。
Readable 接口中的方法:
int read(CharBuffer cb)
read 方法用于尝试将字符读取到指定的 CharBuffer 中,CharBuffer 是一个字符缓冲区,用于存储读取的字符序列。
注意,read 方法返回读取的字符数。如果已到达流的末尾,则返回 -1。如果因为其他原因(如 I/O 错误)而无法读取,则可能抛出 IOException 异常。
以下是一个简单的自定义类 StringReaderWrapper,它实现了 Readable 接口,用于读取一个给定的字符串。代码如下:
package com.hxstrive.java_lang.readable; import java.io.IOException; import java.nio.CharBuffer; /** * Readable 示例,简单的字符串读取器类 * @author hxstrive.com */ public class StringReaderWrapper implements Readable { private String content; private int position; public StringReaderWrapper(String content) { this.content = content; this.position = 0; } @Override public int read(CharBuffer cb) throws IOException { if (position >= content.length()) { return -1; } int remaining = content.length() - position; // 剩余字符数量 int length = Math.min(cb.remaining(), remaining); // 读取字符数量 // 从 content 字符串中读取字符到 CharBuffer 中 content.getChars(position, position + length, cb.array(), cb.arrayOffset() + cb.position()); cb.position(cb.position() + length); position += length; return length; } }
在这个类中,content 是要读取的字符串,position 用于记录当前读取的位置。
read(CharBuffer cb) 方法首先检查是否已经到达字符串的末尾,如果是,则返回 -1。然后计算还剩下多少字符需要读取,以及CharBuffer 还能容纳多少字符,取两者中的较小值作为实际要读取的长度。
接着,将字符串中的字符复制到 CharBuffer 中,更新 CharBuffer 的位置和当前读取位置 position,最后返回实际读取的字符数。
读取自定义的 StringReaderWrapper 类中的内容,代码如下:
package com.hxstrive.java_lang.readable; import java.io.IOException; import java.nio.CharBuffer; /** * Readable 示例,简单的字符串读取器类 * @author hxstrive.com */ public class ReadableDemo { public static void main(String[] args) throws IOException { String content = "Hello, World!"; // 创建自定义的读取器 StringReaderWrapper reader = new StringReaderWrapper(content); // 读取数据 CharBuffer buffer = CharBuffer.allocate(4); int read; do { buffer.clear(); read = reader.read(buffer); buffer.flip(); // 反转 for (int i = 0; i < buffer.limit(); i++) { System.out.print(buffer.get(i)); } System.out.println(); } while (read != -1); } }
运行效果:
在这个示例中,首先创建了一个 StringReaderWrapper 对象,传入要读取的字符串 "Hello, World!"。然后创建了一个容量为 4 的 CharBuffer。通过循环调用 reader.read(buffer) 方法来读取字符到 CharBuffer 中。每次读取前先清空 CharBuffer,读取后翻转 CharBuffer(用于正确读取其中的字符),然后将 CharBuffer 中的字符逐个打印出来,直到 read 方法返回 -1,表示已经读取完所有字符。