仓颉标准库 std.io 输入流接口 InputStream 全面解析:read 读取机制、实现类与配套函数实战
仓颉标准库 std.io 输入流接口 InputStream 全面解析:read 读取机制、实现类与配套函数实战
本指南聚焦于仓颉(Cangjie)语言标准库
std.io包中的核心抽象接口 InputStream(输入流接口)。文章以 InputStream_interface.md 为骨架,结合 io_package_interfaces.md、io_package_classes.md 与 io_samples 中的可验证示例,讲解 InputStream 的接口契约、read 读取机制、周边接口协作关系、标准实现类与配套顶层函数,帮助读者在仓颉程序中正确、高效地完成字节流读取与处理。
一、导读
在仓颉标准库中,std.io 包为程序与外部设备(文件、网络、内存等)之间的数据交换提供了流式 I/O 的统一抽象。InputStream 是所有输入流类型的公共契约:它只声明一个 read 方法,却支撑起了从内存缓冲区、文件、网络等多数据源读取字节的全部能力。阅读本文后,你将掌握 InputStream 的接口定义与 read 语义、它与 OutputStream / IOStream / Seekable 的协作关系、常用实现类(ByteBuffer、BufferedInputStream、ChainedInputStream、StringReader)的选取策略,以及 copy、readToEnd、readString 等配套函数的正确用法,并能够编写出可编译、可运行、可验证的仓颉 I/O 代码。
二、接口定义与 read 方法契约
2.1 接口声明
根据 io_package_interfaces.md 中的完整声明,InputStream 接口定义如下:
public interface InputStream {
func read(buffer: Array<Byte>): Int64
}
整个接口仅包含一个成员函数 read,其原型为 (buffer: Array<Byte>) -> Int64。这与 InputStream_interface.md 中"成员函数"一节记录的签名完全一致。任何希望作为"输入流"参与 I/O 的类型(无论是标准库内置的 ByteBuffer,还是开发者自定义的流类型)都必须实现该方法,这是仓颉流式读取体系的"最小契约"。
2.2 read 方法的参数与返回值语义
read 方法的完整语义如下:
- 参数
buffer: Array<Byte>:一个字节缓冲区,用于存放从输入流中读取的数据。调用方负责预先分配足够的空间;buffer的类型为Array<Byte>,对应仓颉标准库的字节数组(详见 Array 结构体 与 Byte 类型)。 - 返回值
Int64:本次实际读取到的数据字节数。该返回值是判断读取进度的关键:当返回 0 时,通常意味着流中已经没有更多可读数据(流已读完)。
一个实用的读取惯用法是循环调用 read 直至返回 0,这与 chained_input_stream.md 示例中的读取模式一致:先调用一次
read(buffer)拿到readLen,只要readLen != 0就继续读取并累积结果,从而把不确定长度的流完整读完。
三、输入流的周边接口:输出、双向与定位
InputStream 并非孤立存在,它与 std.io 中的另外三个接口共同构成流式 I/O 的抽象体系(全部定义见 io_package_interfaces.md):
3.1 OutputStream——输出流接口
public interface OutputStream {
func write(buffer: Array<Byte>): Unit
func flush(): Unit
}
与 InputStream 的"读出"相对,OutputStream 负责"写入":write 将缓冲区数据写入输出流;flush 清空缓存区,且提供默认实现(默认实现为空),即并非每个实现都必须真正刷新。
3.2 IOStream——输入输出流接口
public interface IOStream <: InputStream & OutputStream {}
IOStream 同时继承 InputStream 与 OutputStream,代表"既可读又可写"的双向流。标准库中的 ByteBuffer 即实现了 IOStream,因此它可以同时充当输入源和输出目标——这在 copy、示例数据回放等场景中非常实用。
3.3 Seekable——移动光标接口
public interface Seekable {
prop length: Int64
prop position: Int64
prop remainLength: Int64
func seek(sp: SeekPosition): Int64
}
Seekable 为流补充了"随机访问"能力:
| 成员 | 类型 | 语义 |
|---|---|---|
prop length |
Int64 |
当前流中的总数据量 |
prop position |
Int64 |
当前光标位置 |
prop remainLength |
Int64 |
当前流中未读的数据量 |
func seek(sp) |
Int64 |
移动光标到指定位置,返回数据起点到移动后位置的字节偏移量 |
seek 的参数类型为 SeekPosition,该枚举定义了三种定位基准(详见 io_package_enums.md):
Begin(Int64):从流数据起点开始移动;Current(Int64):从当前位置开始移动;End(Int64):从流数据末尾开始移动。
需要特别注意的是:只有同时满足 T <: InputStream & Seekable 的流,才能使用 readToEnd、readString 等便捷函数(见下文第五节)。此外,多条 API 文档(如 ByteBuffer 的 seek 说明)都强调:指定位置不能位于流数据头部之前(否则抛出 IOException),但可以超过流数据末尾。
四、InputStream 的标准实现类与选取策略
std.io 提供了多个 InputStream 实现,理解各自的适用场景是实战的关键。以下类型完整定义均可查阅 io_package_classes.md。
4.1 ByteBuffer——内存字节流(最常用的基础实现)
public class ByteBuffer <: IOStream & Seekable {
public init()
public init(capacity: Int64)
public init(source: Array<Byte>)
}
ByteBuffer 基于 Array<Byte> 提供对字节流的写入、读取等操作,同时实现 IOStream 与 Seekable,因此它天然满足 InputStream & Seekable 约束,可直接配合 readToEnd、readString 使用。其构造函数支持三种形式(详见 ByteBuffer_class.md):
init():默认初始容量 32;init(capacity: Int64):指定初始容量(capacity 小于 0 抛出 IllegalArgumentException,错误信息示例:The capacity must be greater than or equal to 0: -1024);init(source: Array<Byte>):根据已有字节数组构造。
一个写入、读取、定位一体的典型用法(源自 byte_buffer.md 示例):
import std.io.*
main(): Unit {
let arr1 = "test case".toArray()
let byteBuffer = ByteBuffer()
/* 将 arr1 中的数据写入到流中 */
byteBuffer.write(arr1)
/* 读取前 4 个字节的数据到 arr2 中 */
let arr2 = Array<Byte>(4, repeat: 0)
byteBuffer.read(arr2)
println(String.fromUtf8(arr2)) // test
/* 将流的索引指向起点 */
byteBuffer.seek(Begin(0))
/* 读取流中全部数据 */
let arr3 = readToEnd(byteBuffer)
println(String.fromUtf8(arr3)) // test case
/* 将流的索引指向字母 'c' 的位置 */
byteBuffer.seek(End(-4))
/* 读取流中剩余数据 */
let str = readString(byteBuffer)
println(str) // case
}
运行结果为:
test
test case
case
注意这里的 byteBuffer.read(arr2) 正是通过 InputStream 接口的 read 方法完成的,而 readToEnd、readString 则依赖于 InputStream & Seekable 双重约束。
4.2 BufferedInputStream——带缓冲区的输入流
public class BufferedInputStream<T> <: InputStream where T <: InputStream {
public init(input: T)
public init(input: T, buffer: Array<Byte>)
public init(input: T, capacity: Int64)
}
BufferedInputStream 将其他 InputStream(如 ByteBuffer)绑定到自身,读取时先把数据从被绑定的流读入缓冲区暂存,再从缓冲区提供给调用方,从而减少底层读取次数。三种构造函数(详见 BufferedInputStream_class.md):
init(input: T):缓冲区容量取默认值 4096;init(input: T, buffer: Array<Byte>):复用调用方传入的缓冲区,在注重性能的场景下可减少内存分配次数(buffer 大小为 0 时抛出 IllegalArgumentException,错误信息:The buffer cannot be empty.);init(input: T, capacity: Int64):指定缓冲区容量(capacity 小于等于 0 时抛出 IllegalArgumentException,错误信息示例:Invalid capacity size: capacity = 0.)。
除 read 外,BufferedInputStream 还提供 readByte(): ?Byte(读取一个字节,失败返回 None)与 reset(input: T)(绑定新的输入流并重置状态,但不重置 capacity)。当被绑定流同时实现 Resource 时,BufferedInputStream 可在 try-with-resource 语法中自动释放资源(close / isClosed);当被绑定流实现 Seekable 时,它还获得 length、position、remainLength、seek 能力,且 seek 调用会先清空缓冲区再移动光标。
基础读取示例(源自 buffered_input_stream.md):
import std.io.*
main(): Unit {
let arr1 = "0123456789".toArray()
let byteBuffer = ByteBuffer()
byteBuffer.write(arr1)
let bufferedInputStream = BufferedInputStream(byteBuffer)
let arr2 = Array<Byte>(20, repeat: 0)
/* 读取流中数据,返回读取到的数据的长度 */
let readLen = bufferedInputStream.read(arr2)
println(String.fromUtf8(arr2[..readLen])) // 0123456789
}
4.3 ChainedInputStream——顺序拼接多个输入流
public class ChainedInputStream<T> <: InputStream where T <: InputStream {
public init(input: Array<T>)
}
ChainedInputStream 提供顺序从 InputStream 数组中读取数据的能力:当绑定数组中的前一个流读完后,自动切换到下一个流继续读取(绑定数组为空时抛出 IllegalArgumentException)。它非常适合把多个数据段拼成一个逻辑上的连续流。完整示例见 chained_input_stream.md,其输出为 now 0now 1。
4.4 StringReader——面向字符的输入流封装
public class StringReader<T> where T <: InputStream {
public init(input: T)
}
StringReader 提供从 InputStream 读出数据并转换成字符或字符串的能力(详见 io_package_classes.md),适合文本处理场景:
- 内部默认有缓冲区,容量 4096 字节;
- 目前仅支持 UTF-8 编码,暂不支持 UTF-16、UTF-32;
- 常用方法:
read(): ?Rune(按字符读取)、readln(): Option<String>(按行读取,去掉换行符)、readToEnd(): String、readUntil(Rune)/readUntil((Rune)->Bool)(读到指定字符为止)、lines(): Iterator<String>、runes(): Iterator<Rune>; - 读取到非法 UTF-8 字符时抛出 ContentFormatException;
- 当被绑定流实现 Resource / Seekable 时,StringReader 相应获得
try-with-resource资源释放与光标定位能力。
文本读取示例(源自 string_reader.md):
import std.io.*
main(): Unit {
let arr1 = "012\n346789".toArray()
let byteBuffer = ByteBuffer()
byteBuffer.write(arr1)
let stringReader = StringReader(byteBuffer)
/* 读取一个字符 */
let ch = stringReader.read()
println(ch ?? 'a') // 0
/* 读取一行数据 */
let line = stringReader.readln()
println(line ?? "error") // 12
/* 读取数据直到遇到字符6 */
let until = stringReader.readUntil(r'6')
println(until ?? "error") // 346
/* 读取全部数据 */
let all = stringReader.readToEnd()
println(all) // 789
}
五、InputStream 的配套顶层函数
std.io 还提供了一组以 InputStream 为核心的顶层函数,使常见的"读到底""读成字符串""流拷贝"操作一行搞定。全部定义见 io_package_funcs.md。
5.1 readToEnd——读取全部剩余字节
public func readToEnd<T>(from: T): Array<Byte> where T <: InputStream & Seekable
获取入参中未被读取的数据的拷贝,返回 Array<Byte>。注意其约束条件为 T <: InputStream & Seekable,因此只能用于 ByteBuffer 这类同时具备定位能力的流。示例:
import std.io.ByteBuffer
import std.io.readToEnd
main(): Unit {
let inputStream = ByteBuffer()
let sourceData = "Hello, World!".toArray()
inputStream.write(sourceData)
/* 使用 readToEnd 函数读取输入流中的所有剩余内容 */
let data = readToEnd(inputStream)
println("${String.fromUtf8(data)}") // Hello, World!
}
5.2 readString 与 readStringUnchecked——读取并转为字符串
public func readString<T>(from: T): String where T <: InputStream & Seekable
public unsafe func readStringUnchecked<T>(from: T): String where T <: InputStream & Seekable
readString:读取入参中的所有剩余内容并返回字符串;当剩余字节不符合 UTF-8 编码规则时抛出ContentFormatException(错误信息示例:Invalid unicode scalar value.)。readStringUnchecked:功能相同,但不检查字符串的合法性,须在unsafe上下文中调用;当输入流首位是不合法的 UTF-8 字符时,会产生不可预期的输出字符,属于高风险接口,仅在确定数据合法时使用。
5.3 copy——输入流到输出流的批量拷贝
public func copy(from: InputStream, to!: OutputStream): Int64
将一个输入流中未被读取的数据拷贝到另一个输出流中,返回拷贝的字节数。它是"读-写"组合的标准工具,示例(源自 io_package_funcs.md):
import std.io.ByteBuffer
import std.io.copy
main(): Unit {
let sourceStream = ByteBuffer()
let targetStream = ByteBuffer()
/* 向源输入流写入数据 */
let sourceData = "Hello, World!".toArray()
sourceStream.write(sourceData)
/* 使用 copy 函数将源输入流的数据拷贝到目标输出流 */
let copiedBytes = copy(sourceStream, to: targetStream)
println("Copied ${copiedBytes} bytes.")
/* 读取目标输出流中的数据 */
let targetData: Array<Byte> = Array<Byte>(sourceData.size, repeat: 0)
targetStream.read(targetData)
println("Data copied to target stream: ${String.fromUtf8(targetData)}")
}
运行结果:
Copied 13 bytes.
Data copied to target stream: Hello, World!
值得注意的是,copy 的参数 from 类型仅为 InputStream(不要求 Seekable),因此它比 readToEnd 等函数的适用范围更宽——任何实现了 InputStream 的流都可以作为拷贝源。
六、输入流的异常处理体系
围绕 InputStream 的读取操作,std.io 定义了两种异常(详见 io_package_exceptions.md):
| 异常类 | 继承关系 | 触发场景 |
|---|---|---|
IOException |
<: Exception(open 类,可派生) |
IO 流相关错误,如 seek 试图移动到流数据头部之前(错误信息:Can't move the position before the beginning of the stream.) |
ContentFormatException |
<: Exception |
字符格式相关错误,如 readString / StringReader 读到非法 UTF-8 字符 |
两者均支持 init() 与 init(message: String) 两种构造方式,IOException 还提供 getClassName() 用于获取类名。在实战中,建议对涉及文本解码的读取(readString、StringReader 系列方法)捕获 ContentFormatException,对涉及光标定位的操作(seek)捕获 IOException,例如 io_package_funcs.md 中 readString 示例的写法:
try {
let result = readString(inputStream)
println("Read string: ${result}")
} catch (e: ContentFormatException) {
println("Error: ${e.message}")
}
七、自定义 InputStream:扩展自己的输入源
InputStream 只有单一方法契约,因此开发者可以非常轻量地实现自定义输入流。以 io_package_classes.md 中 BufferedInputStream 的 Seekable 示例为参考,自定义类只需实现 read 即可接入整个 std.io 生态(例如被 BufferedInputStream 包装获得缓冲能力,或作为 copy 的源):
public class A <: InputStream & Seekable {
public var inputStream: ByteBuffer = ByteBuffer()
public func read(buffer: Array<Byte>): Int64 {
let inputData = "Hello World".toArray()
inputStream = ByteBuffer(inputData)
let num = inputStream.read(buffer)
return num
}
public func seek(sp: SeekPosition): Int64 {
return inputStream.seek(sp)
}
}
结合 BufferedInputStream 包装后,即可通过 length、position、remainLength 查询状态,并通过 seek(SeekPosition.Current(11)) 等调用移动光标。该示例的运行输出(详见 io_package_classes.md 对应示例)为:
Length : 11
Position : 11
Remain Length : 0
Position after seek() : 22
Error: Can't move the position before the beginning of the stream.
World
八、总结:InputStream 使用速查
- 最小契约:实现
func read(buffer: Array<Byte>): Int64即可成为输入流;返回值表示实际读取字节数,读到 0 表示流已读完。 - 接口选型:只读用 InputStream;读写双向用 IOStream;需要随机访问(读到底、定位)再叠加 Seekable,并配合
Begin / Current / End三种 SeekPosition 基准。 - 实现类选择:内存数据用 ByteBuffer;需要减少底层读取次数用 BufferedInputStream(默认缓冲区 4096,可复用 buffer 或指定 capacity);多段数据拼接用 ChainedInputStream;文本按字符/行读取用 StringReader(仅支持 UTF-8)。
- 便捷函数:
readToEnd/readString要求InputStream & Seekable;readStringUnchecked跳过 UTF-8 合法性检查(unsafe);copy只要求 InputStream 即可完成流间拷贝。 - 异常纪律:文本解码异常捕获
ContentFormatException,光标定位越界捕获IOException;seek 不允许越过数据头部之前,但允许越过数据末尾。 - 继续深入:完整 API 见 io_package_interfaces.md 与 io_package_classes.md;可直接运行的示例见 io_samples 目录(含 buffered_input_stream、byte_buffer、chained_input_stream、string_reader、string_writer 等)。