Classes
class BufferedInputStream<T> where T <: InputStream
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)
}
Description: Provides input streams with buffers.
This class supports binding the input stream of other InputStream types (such as ByteBuffer) to the BufferedInputStream instance. When data is read from the instance, the data is read from the bound stream to the buffer for temporary storage, and then the required data is read from the buffer.
Parent types:
init(T)
public init(input: T)
Description: Creates a BufferedInputStream instance. The default buffer size is 4096.
Parameters:
- input: T: bound input stream
Examples:
import std.io.ByteBuffer
import std.io.BufferedInputStream
main(): Unit {
let inputData = "Hello World".toArray()
let inputStream = ByteBuffer(inputData)
/* Bind to a specified input stream. */
let bufferedStream = BufferedInputStream(inputStream)
/* Read data from the input stream. */
let data = Array<Byte>(inputData.size, repeat: 0)
bufferedStream.read(data)
println(String.fromUtf8(data))
}
Results:
Hello World
init(T, Array<Byte>)
public init(input: T, buffer: Array<Byte>)
Description: Creates a BufferedInputStream instance.
The internal buffer is determined by the input parameter. In performance-oriented scenarios, the input buffer can be reused to reduce the number of memory allocation times for better performance.
Parameters:
- input: T: bound input stream
- buffer: Array<Byte>: internal buffer used by BufferedInputStream
Throws:
- IllegalArgumentException: If the buffer size is equal to 0, this exception is thrown.
Examples:
import std.io.ByteBuffer
import std.io.BufferedInputStream
main(): Unit {
let inputStream = ByteBuffer()
/* When a BufferedInputStream instance is created in a valid internal buffer, no exception is thrown. */
try {
let buffer = Array<Byte>(1024, repeat: 0)
let bufferedStream = BufferedInputStream(inputStream, buffer)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
/* The size of the internal buffer is defined as 0. */
try {
let invalidBuffer = Array<Byte>()
let bufferedStream = BufferedInputStream(inputStream, invalidBuffer)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
}
Results:
Error: The buffer cannot be empty.
init(T, Int64)
public init(input: T, capacity: Int64)
Description: Creates a BufferedInputStream instance.
Parameters:
- input: T: bound input stream
- capacity: Int64: size of the internal buffer
Throws:
- IllegalArgumentException: If the value of capacity is less than or equal to 0, this exception is thrown.
func read(Array<Byte>)
public func read(buffer: Array<Byte>): Int64
Description: Reads data from the bound input stream to buffer.
Parameters:
Returns:
- Int64: number of bytes of the read data
Throws:
- IllegalArgumentException: If buffer is empty, this exception is thrown.
Examples:
import std.io.ByteBuffer
import std.io.BufferedInputStream
main(): Unit {
let inputStream = ByteBuffer()
/* When a BufferedInputStream instance is created within the valid internal buffer capacity, no exception is thrown. */
try {
let capacity = 2048
let bufferedStream = BufferedInputStream(inputStream, capacity)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
/* When the internal buffer is set to 0, an exception is thrown. */
try {
let zeroCapacity = 0
let bufferedStream = BufferedInputStream(inputStream, zeroCapacity)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
/* When the internal buffer is set to a negative number, an exception is thrown. */
try {
let negativeCapacity = -1024
let bufferedStream = BufferedInputStream(inputStream, negativeCapacity)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
}
Results:
Error: Invalid capacity size: capacity = 0.
Error: Invalid capacity size: capacity = -1024.
func readByte()
public func readByte(): ?Byte
Description: Reads a byte from the input stream.
Returns:
- ?Byte: data read. If the read operation fails,
Noneis returned.
Examples:
import std.io.ByteBuffer
import std.io.BufferedInputStream
main(): Unit {
/* Create an input stream and write data. */
let inputStream = ByteBuffer()
let sourceData = "abc".toArray()
inputStream.write(sourceData)
let bufferedStream = BufferedInputStream(inputStream)
/* Read all bytes in sequence. */
while (true) {
let byte = bufferedStream.readByte()
if (byte == None) {
break
}
println(String.fromUtf8(byte.getOrThrow()))
}
}
Results:
a
b
c
func reset(T)
public func reset(input: T): Unit
Description: Binds a new input stream and resets the status without resetting capacity.
Parameters:
- input: T: input stream to be bound
Examples:
import std.io.ByteBuffer
import std.io.BufferedInputStream
import std.io.IOException
main(): Unit {
/* Create the first input stream and write data. */
let inputStream1 = ByteBuffer()
let sourceData1 = "First message: Hello".toArray()
inputStream1.write(sourceData1)
/* Create the second input stream and write data. */
let inputStream2 = ByteBuffer()
let sourceData2 = "Second message: World".toArray()
inputStream2.write(sourceData2)
/* Use BufferedInputStream to wrap the first input stream. */
let bufferedStream = BufferedInputStream(inputStream1)
/* Read partial data of the first input stream. */
var result1 = ""
for (_ in 0..sourceData1.size) {
let byte = bufferedStream.readByte()
if (byte == None) {
break
}
result1 += String.fromUtf8(byte.getOrThrow())
}
println(result1)
/* Reset the input stream to the second input stream. */
bufferedStream.reset(inputStream2)
var result2 = ""
for (_ in 0..sourceData2.size) {
let byte = bufferedStream.readByte()
if (byte == None) {
break
}
result2 += String.fromUtf8(byte.getOrThrow())
}
println(result2)
}
Results:
First message: Hello
Second message: World
extend<T> BufferedInputStream<T> <: Resource where T <: Resource
extend<T> BufferedInputStream<T> <: Resource where T <: Resource
Description: Implements the Resource interface for BufferedInputStream. This type of object can implement automatic resource release in the try-with-resource syntax context.
Parent types:
func close()
public func close(): Unit
Description: Closes the current stream.
NOTE
- After this method is called, other interfaces of BufferedInputStream cannot be called. Otherwise, unexpected problems may occur.
func isClosed()
public func isClosed(): Bool
Description: Checks whether the current stream is closed.
Returns:
- Bool: true: yes, false: no
Examples:
import std.io.BufferedInputStream
import std.io.InputStream
import std.io.ByteBuffer
/**
* Define class A to implement the InputStream and Resource APIs.
*/
public class A <: InputStream & Resource {
private var closed: Bool = false
public func read(buffer: Array<Byte>): Int64 {
let inputData = "Hello World".toArray()
let inputStream = ByteBuffer(inputData)
let num = inputStream.read(buffer)
return num
}
public func isClosed(): Bool {
return closed
}
public func close(): Unit {
println("Resource is closed")
closed = true
}
}
main(): Unit {
let bufferedStream = BufferedInputStream(A())
/* Use the try-with-resource statement to obtain resources. */
try (r = bufferedStream) {
println("Get the resource")
let data = Array<Byte>(11, repeat: 0)
r.read(data)
println(r.isClosed())
println(String.fromUtf8(data))
}
/* The close () function is automatically called to release resources. */
println(bufferedStream.isClosed())
}
Results:
Get the resource
false
Hello World
Resource is closed
true
extend<T> BufferedInputStream<T> <: Seekable where T <: Seekable
extend<T> BufferedInputStream<T> <: Seekable where T <: Seekable
Description: Implements the Seekable interface for BufferedInputStream to implement operations such as querying data length and moving the cursor.
Parent types:
prop length
public prop length: Int64
Description: Returns the total data volume of the current stream.
Type: Int64
prop position
public prop position: Int64
Description: Returns the current cursor position.
Type: Int64
prop remainLength
public prop remainLength: Int64
Description: Returns the unread data volume in the current stream.
Type: Int64
func seek(SeekPosition)
public func seek(sp: SeekPosition): Int64
Description: Moves the cursor to a specified position.
NOTE
- The specified position cannot be before the data header in the stream.
- The specified position can be after the end of the data in the stream.
- If this function is called, the buffer is cleared before the cursor is moved.
Parameters:
- sp: SeekPosition: the position to which the cursor is to be moved
Returns:
- Int64: the offset (in bytes) from the start point of the data in the stream to the position after the cursor is moved
Throws:
- IOException: If the specified position is before the data header in the stream, this exception is thrown.
Examples:
import std.io.BufferedInputStream
import std.io.InputStream
import std.io.ByteBuffer
import std.io.Seekable
import std.io.SeekPosition
import std.io.IOException
import std.io.readToEnd
/**
* Define class A to implement the InputStream and Seekable APIs.
*/
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)
}
}
main(): Unit {
let seekableStream = A()
let bufferedStream = BufferedInputStream(seekableStream)
let buffer = Array<Byte>(11, repeat: 0)
bufferedStream.read(buffer)
/* Output the total data volume in the current stream, the current cursor position, and the unread data volume in the current stream. */
println("Length : " + bufferedStream.length.toString())
println("Position : " + bufferedStream.position.toString())
println("Remain Length : " + bufferedStream.remainLength.toString())
/* Move the cursor to the specified position. The position is valid even if it exceeds the end of the data in the stream. */
println("Position after seek() : " + bufferedStream.seek(SeekPosition.Current(11)).toString())
/* Before you try to move the cursor to the beginning of the data, an exception is thrown. */
try {
bufferedStream.seek(SeekPosition.Begin(-1))
} catch (e: IOException) {
println("Error: " + e.message)
}
/* Move the cursor to the end of the first word and read the subsequent data. */
bufferedStream.seek(SeekPosition.Begin(6))
println(String.fromUtf8(readToEnd(seekableStream.inputStream)))
}
Results:
Length : 11
Position : 11
Remain Length : 0
Position after seek() : 22
Error: Cannot move the position before the beginning of the stream.
World
class BufferedOutputStream<T> where T <: OutputStream
public class BufferedOutputStream<T> <: OutputStream where T <: OutputStream {
public init(output: T)
public init(output: T, buffer: Array<Byte>)
public init(output: T, capacity: Int64)
}
Description: Provides output streams with buffers.
This class supports binding the input stream of the OutputStream type (such as ByteBuffer) to a BufferedOutputStream instance. When data is written by using the instance, the data is written to the buffer for temporary storage, and then written from the buffer to the stream.
Parent types:
init(T)
public init(output: T)
Description: Creates a BufferedOutputStream instance. The default buffer size is 4096.
Parameters:
- output: T: bound output stream
Examples:
import std.io.ByteBuffer
import std.io.BufferedOutputStream
import std.io.readToEnd
main(): Unit {
let outputStream = ByteBuffer()
/* Bind a specified output stream. */
let bufferedStream = BufferedOutputStream(outputStream)
/* Write the output data to the buffered stream bufferedStream and refresh the internally bound output stream outputStream. */
let outputData = "Hello World".toArray()
bufferedStream.write(outputData)
bufferedStream.flush()
println(String.fromUtf8(readToEnd(outputStream)))
}
Results:
Hello World
init(T, Array<Byte>)
public init(output: T, buffer: Array<Byte>)
Description: Creates a BufferedOutputStream instance.
The internal buffer is determined by the input parameter. In performance-oriented scenarios, the input buffer can be reused to reduce the number of memory allocation times for better performance.
Parameters:
- output: T: bound output stream
- buffer: Array<Byte>: internal buffer used by BufferedOutputStream
Throws:
- IllegalArgumentException: If the buffer size is equal to 0, this exception is thrown.
Examples:
import std.io.ByteBuffer
import std.io.BufferedOutputStream
main(): Unit {
let outputStream = ByteBuffer()
/* When a BufferedOutputStream instance is created in a valid internal buffer, no exception is thrown. */
try {
let buffer = Array<Byte>(1024, repeat: 0)
let bufferedStream = BufferedOutputStream(outputStream, buffer)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
/* The size of the internal buffer is defined as 0. */
try {
let invalidBuffer = Array<Byte>()
let bufferedStream = BufferedOutputStream(outputStream, invalidBuffer)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
}
Results:
Error: The buffer cannot be empty.
init(T, Int64)
public init(output: T, capacity: Int64)
Description: Creates a BufferedOutputStream instance.
Parameters:
- output: T: bound output stream
- capacity: Int64: size of the internal buffer
Throws:
- IllegalArgumentException: If the value of capacity is less than or equal to 0, this exception is thrown.
Examples:
import std.io.ByteBuffer
import std.io.BufferedOutputStream
main(): Unit {
let outputStream = ByteBuffer()
/* When a BufferedOutputStream instance is created within the valid internal buffer capacity, no exception is thrown. */
try {
let capacity = 2048
let bufferedStream = BufferedOutputStream(outputStream, capacity)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
/* When the internal buffer is set to 0, an exception is thrown. */
try {
let zeroCapacity = 0
let bufferedStream = BufferedOutputStream(outputStream, zeroCapacity)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
/* When the internal buffer is set to a negative number, an exception is thrown. */
try {
let negativeCapacity = -1024
let bufferedStream = BufferedOutputStream(outputStream, negativeCapacity)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
}
Results:
Error: Invalid capacity size: capacity = 0.
Error: Invalid capacity size: capacity = -1024.
func flush()
public func flush(): Unit
Description: Refreshes BufferedOutputStream. Writes the remaining data in the internal buffer to the bound output stream and refreshes BufferedOutputStream.
Examples:
import std.io.ByteBuffer
import std.io.BufferedOutputStream
import std.io.readToEnd
main(): Unit {
let outputStream = ByteBuffer()
/* Bind a specified output stream. */
let bufferedStream = BufferedOutputStream(outputStream)
/* Write the output data to the buffered stream bufferedStream and refresh the internally bound output stream outputStream. */
let outputData = "Hello World".toArray()
bufferedStream.write(outputData)
bufferedStream.flush()
println(String.fromUtf8(readToEnd(outputStream)))
}
Results:
Hello World
func reset(T)
public func reset(output: T): Unit
Description: Binds a new output stream and resets the status without resetting capacity.
Parameters:
- output: T: output stream to be bound
Examples:
import std.io.ByteBuffer
import std.io.BufferedOutputStream
import std.io.IOException
import std.io.readToEnd
main(): Unit {
/* Create the first output stream. */
let outputStream1 = ByteBuffer()
let sourceData1 = "First message: Hello".toArray()
/* Create the second output stream. */
let outputStream2 = ByteBuffer()
let sourceData2 = "Second message: World".toArray()
/* Use BufferedOutputStream to wrap the first output stream. */
let bufferedStream = BufferedOutputStream(outputStream1)
/* Write the first source data to the first bound output stream and refresh the data. */
bufferedStream.write(sourceData1)
bufferedStream.flush()
println(String.fromUtf8(readToEnd(outputStream1)))
/* Reset the output stream to the second output stream, write the second source data to the second bound output stream, and refresh the data. */
bufferedStream.reset(outputStream2)
bufferedStream.write(sourceData2)
bufferedStream.flush()
println(String.fromUtf8(readToEnd(outputStream2)))
}
Results:
First message: Hello
Second message: World
func write(Array<Byte>)
public func write(buffer: Array<Byte>): Unit
Description: Writes data in buffer to the bound output stream.
Parameters:
Examples:
import std.io.ByteBuffer
import std.io.BufferedOutputStream
import std.io.readToEnd
main(): Unit {
let outputStream = ByteBuffer()
/* Bind a specified output stream. */
let bufferedStream = BufferedOutputStream(outputStream)
/* Write the output data to the buffered stream bufferedStream and refresh the internally bound output stream outputStream. */
let outputData = "Hello World".toArray()
bufferedStream.write(outputData)
bufferedStream.flush()
println(String.fromUtf8(readToEnd(outputStream)))
}
Results:
Hello World
func writeByte(Byte)
public func writeByte(v: Byte): Unit
Description: Writes a byte to the bound output stream.
Parameters:
- v: Byte: byte to be written
Examples:
import std.io.ByteBuffer
import std.io.BufferedOutputStream
import std.io.readToEnd
main(): Unit {
let outputStream = ByteBuffer()
/* Bind a specified output stream. */
let bufferedStream = BufferedOutputStream(outputStream)
/* Write the output data to the buffered stream bufferedStream one by one and refresh the internally bound output stream outputStream. */
let outputData = "Hello World".toArray()
for (byte in outputData){
bufferedStream.writeByte(byte)
}
bufferedStream.flush()
println(String.fromUtf8(readToEnd(outputStream)))
}
Results:
Hello World
extend<T> BufferedOutputStream<T> <: Resource where T <: Resource
extend<T> BufferedOutputStream<T> <: Resource where T <: Resource
Description: Implements the Resource interface for BufferedOutputStream. This type of object can implement automatic resource release in the try-with-resource syntax context.
Parent types:
func close()
public func close(): Unit
Description: Closes the current stream.
NOTE
- After this method is called, other interfaces of BufferedOutputStream cannot be called. Otherwise, unexpected problems may occur.
func isClosed()
public func isClosed(): Bool
Description: Checks whether the current stream is closed.
Returns:
- Bool: true: yes, false: no
Examples:
import std.io.BufferedOutputStream
import std.io.OutputStream
import std.io.ByteBuffer
import std.io.readToEnd
/**
* Define class A to implement the OutputStream and Resource APIs.
*/
public class A <: OutputStream & Resource {
private var closed: Bool = false
public var outputStream = ByteBuffer()
public func write(buffer: Array<Byte>): Unit {
this.outputStream = ByteBuffer(buffer)
}
public func isClosed(): Bool {
return closed
}
public func close(): Unit {
println("Resource is closed")
closed = true
}
}
main(): Unit {
let resourceStream = A()
let bufferedStream = BufferedOutputStream(resourceStream)
/* Use the try-with-resource statement to obtain resources. */
try (r = bufferedStream) {
println("Get the resource")
let data = "Hello World".toArray()
r.write(data)
r.flush()
println(r.isClosed())
println(String.fromUtf8(readToEnd(resourceStream.outputStream)))
}
/* The close () function is automatically called to release resources. */
println(bufferedStream.isClosed())
}
Results:
Get the resource
false
Hello World
Resource is closed
true
extend<T> BufferedOutputStream<T> <: Seekable where T <: Seekable
extend<T> BufferedOutputStream<T> <: Seekable where T <: Seekable
Description: Implements the Seekable interface for BufferedOutputStream to implement operations such as querying data length and moving the cursor.
Parent types:
prop length
public prop length: Int64
Description: Returns the total data volume of the current stream.
Type: Int64
prop position
public prop position: Int64
Description: Returns the current cursor position.
Type: Int64
prop remainLength
public prop remainLength: Int64
Description: Returns the unread data volume in the current stream.
Type: Int64
func seek(SeekPosition)
public func seek(sp: SeekPosition): Int64
Description: Moves the cursor to a specified position.
NOTE
- The specified position cannot be before the data header in the stream.
- The specified position can be after the end of the data in the stream.
- When this function is called, the data in the buffer is written to the bound output stream before the cursor is moved.
Parameters:
- sp: SeekPosition: the position to which the cursor is to be moved
Returns:
- Int64: the offset (in bytes) from the start point of the data in the stream to the position after the cursor is moved
Throws:
- IOException: If the specified position is before the data header in the stream, this exception is thrown.
Examples:
import std.io.BufferedOutputStream
import std.io.OutputStream
import std.io.ByteBuffer
import std.io.Seekable
import std.io.SeekPosition
import std.io.IOException
import std.io.readToEnd
/**
* Define class A to implement the OutputStream and Seekable APIs.
*/
public class A <: OutputStream & Seekable {
public var outputStream: ByteBuffer = ByteBuffer()
public func write(buffer: Array<Byte>): Unit {
this.outputStream = ByteBuffer(buffer)
}
public func seek(sp: SeekPosition): Int64 {
return outputStream.seek(sp)
}
}
main(): Unit {
let seekableStream = A()
let bufferedStream = BufferedOutputStream(seekableStream)
let data = "Hello World".toArray()
bufferedStream.write(data)
bufferedStream.flush()
/* Output the total data volume in the current stream, the current cursor position, and the unread data volume in the current stream. */
println("Length : " + bufferedStream.length.toString())
println("Position : " + bufferedStream.position.toString())
println("Remain Length : " + bufferedStream.remainLength.toString())
/* Move the cursor to the specified position. The position is valid even if it exceeds the end of the data in the stream. */
println("Position after seek() : " + bufferedStream.seek(SeekPosition.Current(11)).toString())
/* Before you try to move the cursor to the beginning of the data, an exception is thrown. */
try {
bufferedStream.seek(SeekPosition.Begin(-1))
} catch (e: IOException) {
println("Error: " + e.message)
}
/* Move the cursor to the end of the first word and read the subsequent data. */
bufferedStream.seek(SeekPosition.Begin(6))
println(String.fromUtf8(readToEnd(seekableStream.outputStream)))
}
Results:
Length : 11
Position : 0
Remain Length : 11
Position after seek() : 11
Error: Cannot move the position before the beginning of the stream.
World
class ByteBuffer
public class ByteBuffer <: IOStream & Seekable {
public init()
public init(capacity: Int64)
public init(source: Array<Byte>)
}
Description: Writes and reads byte streams based on the Array<Byte> data type.
Parent types:
prop capacity
public prop capacity: Int64
Description: Obtains the current buffer capacity.
Returns:
- Int64: current buffer capacity
init()
public init()
Description: Creates a ByteBuffer instance. The initial capacity is 32 by default.
Examples:
import std.io.ByteBuffer
main(): Unit {
let buffer = ByteBuffer()
println(buffer.capacity)
}
Results:
32
init(Array<Byte>)
public init(source: Array<Byte>)
Description: Constructs a ByteBuffer instance based on the passed array.
Parameters:
Examples:
import std.io.ByteBuffer
main(): Unit {
let inputData = "Hello World".toArray()
let buffer = ByteBuffer(inputData)
println(buffer.capacity)
/* Read data from the buffer. */
println(String.fromUtf8(buffer.bytes()))
}
Results:
11
Hello World
init(Int64)
public init(capacity: Int64)
Description: Creates a ByteBuffer instance.
Parameters:
- capacity: Int64: specified initial capacity
Throws:
- IllegalArgumentException: If the value of capacity is less than 0, this exception is thrown.
Examples:
import std.io.ByteBuffer
main(): Unit {
let buffer = ByteBuffer(1024)
println(buffer.capacity)
try{
let errorBuffer = ByteBuffer(-1024)
println(errorBuffer.capacity)
}catch(e: Exception){
println("Error: ${e.message}")
}
}
Results:
1024
Error: The capacity must be greater than or equal to 0: -1024.
func bytes()
public func bytes(): Array<Byte>
Description: Obtains the slice of the unread data in the current ByteBuffer.
NOTE
- Modifications such as reading, writing, or resetting the buffer will invalidate the slice.
- Modifications to a slice affect the content of the buffer.
Returns:
Examples:
import std.io.ByteBuffer
main(): Unit {
let inputData = "Hello World".toArray()
let buffer = ByteBuffer(inputData)
/* Read data from the buffer. */
println(String.fromUtf8(buffer.bytes()))
}
Results:
Hello World
func clear()
public func clear(): Unit
Description: Clears all data in the current ByteBuffer.
Examples:
import std.io.ByteBuffer
main(): Unit {
let inputData = "Hello World".toArray()
let buffer = ByteBuffer(inputData)
println(buffer.capacity)
/* Read raw data. */
println(String.fromUtf8(buffer.bytes()))
/* Clear the buffer. */
buffer.clear()
/* Read the cleared buffer. */
println("buffer after clear: " + String.fromUtf8(buffer.bytes()))
println("capacity after clear: ${buffer.capacity}")
}
Results:
11
Hello World
buffer after clear:
capacity after clear: 11
func clone()
public func clone(): ByteBuffer
Description: Constructs a new ByteBuffer using the data in the current ByteBuffer.
Returns:
- ByteBuffer: new ByteBuffer object
Examples:
import std.io.ByteBuffer
main(): Unit {
let inputData = "Hello World".toArray()
let originalBuffer = ByteBuffer(inputData)
/* Clone the original buffer. */
let clonedBuffer = originalBuffer.clone()
println("originalBuffer: " + String.fromUtf8(originalBuffer.bytes()))
println("clonedBuffer: " + String.fromUtf8(clonedBuffer.bytes()))
/* Modify the data in the original buffer. */
originalBuffer.write(" New Data".toArray())
println("originalBuffer: " + String.fromUtf8(originalBuffer.bytes()))
println("clonedBuffer: " + String.fromUtf8(clonedBuffer.bytes()))
}
Results:
originalBuffer: Hello World
clonedBuffer: Hello World
originalBuffer: Hello World New Data
clonedBuffer: Hello World
func read(Array<Byte>)
public func read(buffer: Array<Byte>): Int64
Description: Reads data from the input stream and stores the data in buffer.
Parameters:
Returns:
- Int64: number of bytes of the read data
Throws:
- IllegalArgumentException: If buffer is empty, this exception is thrown.
Examples:
import std.io.ByteBuffer
main(): Unit {
let inputData = "Hello World".toArray()
let buffer = ByteBuffer(inputData)
/* Create a target buffer and read data to the target buffer. */
let targetBuffer = Array<Byte>(5,repeat:0)
buffer.read(targetBuffer)
println(String.fromUtf8(targetBuffer))
/* Try to read an empty buffer. */
try {
let emptyBuffer = Array<Byte>()
buffer.read(emptyBuffer)
} catch (e: IllegalArgumentException) {
println("Error: " + e.message)
}
}
Results:
Hello
Error: The buffer is empty.
func readByte()
public func readByte(): ?Byte
Description: Reads a byte from the input stream.
Returns:
- ?Byte: data read. If the read operation fails,
Noneis returned.
Examples:
import std.io.ByteBuffer
main(): Unit {
let inputData = "Hello World".toArray()
let buffer = ByteBuffer(inputData)
for (_ in 0..inputData.size) {
print(String.fromUtf8(buffer.readByte().getOrThrow()))
}
println()
/* Try to read the next byte that does not exist. */
let nextByte = buffer.readByte()
match (nextByte) {
case None => println("nextByte: None")
case _ => println("nextByte: ${nextByte.getOrThrow()}")
}
}
Results:
Hello World
nextByte: None
func reserve(Int64)
public func reserve(additional: Int64): Unit
Description: Expands the buffer by a specified size.
NOTE
- If the number of remaining bytes in the buffer is greater than or equal to
additional, capacity expansion is not performed.- If the number of remaining bytes in the buffer is less than
additional, the buffer is expanded to the larger value between (additional+capacity) and (1.5 times the rounded-down value ofcapacity).
Parameters:
- additional: Int64: size by which the buffer is to be expanded
Throws:
- IllegalArgumentException: If the value of additional is less than 0, this exception is thrown.
- OverflowException: If the buffer size after capacity expansion is greater than the maximum value of Int64, this exception is thrown.
Examples:
import std.io.ByteBuffer
main(): Unit {
let buffer = ByteBuffer(11)
println("initial capacity: " + buffer.capacity.toString())
buffer.write("Hello World".toArray())
/* Try to expand the capacity. The capacity is expanded when the capacity to be increased is greater than the remaining capacity. The expansion is successful. */
buffer.reserve(5)
println("reserve 5: " + buffer.capacity.toString())
/* Attempt to expand the capacity. The capacity is not expanded when the capacity to be increased is less than the remaining capacity. The expansion fails. */
buffer.reserve(2)
println("reserve 2: " + buffer.capacity.toString())
/* Try to expand the capacity. The value of **additional** is a negative number. */
try {
buffer.reserve(-1)
} catch (e: IllegalArgumentException) {
println("Error: " + e.message)
}
/* Try to expand the capacity. As a result, the capacity exceeds the maximum value of Int64. */
try {
buffer.reserve(Int64.Max - buffer.capacity + 1)
} catch (e: OverflowException) {
println("Error: " + e.message)
}
}
Results:
initial capacity: 11
reserve 5: 16
reserve 2: 16
Error: The additional must be greater than or equal to 0.
Error:The maximum value for capacity expansion cannot exceed the maximum value of Int64.
func seek(SeekPosition)
public func seek(sp: SeekPosition): Int64
Description: Moves the cursor to a specified position.
NOTE
- The specified position cannot be before the data header in the stream.
- The specified position can be after the end of the data in the stream.
Parameters:
- sp: SeekPosition: the position to which the cursor is to be moved
Returns:
- Int64: the offset (in bytes) from the data header in the stream to the position to which the cursor is moved
Throws:
- IOException: If the specified position is before the data header in the stream, this exception is thrown.
Examples:
import std.io.ByteBuffer
import std.io.SeekPosition
import std.io.IOException
main(): Unit {
let buffer = ByteBuffer("Hello World".toArray())
println("initial position: ${buffer.position}")
/* Move to 6 bytes after the current position. */
buffer.seek(SeekPosition.Current(6))
println(String.fromUtf8(buffer.bytes()))
/* If the position after the movement exceeds the end of the data in the stream, this is still a valid operation. */
println(buffer.seek(SeekPosition.End(1)))
/* Before you try to move the cursor to the beginning of the data, an exception is thrown. */
try {
buffer.seek(SeekPosition.Begin(-1))
} catch (e: IOException) {
println("Error: " + e.message)
}
}
Results:
initial position: 0
World
12
Error: Cannot move the position before the beginning of the stream.
func setLength(Int64)
public func setLength(length: Int64): Unit
Description: Changes the length of the current data to a specified value. This operation does not change the offset of func seek.
Parameters:
- length: Int64: length to be modified
Throws:
- IllegalArgumentException: If
lengthis less than 0, this exception is thrown. - OverflowException: If the buffer size after capacity expansion exceeds the maximum value of Int64 because the value of length is too large, this exception is thrown.
Examples:
import std.io.ByteBuffer
main(): Unit {
let buffer = ByteBuffer("Hello World".toArray())
println("initial length: " + buffer.length.toString())
/* Set the length to 5 and read all content in the buffer. */
buffer.setLength(5)
println("set length to 5: " + String.fromUtf8(buffer.bytes()))
/* When the buffer size after capacity expansion exceeds the maximum value of Int64, an exception is thrown. */
try {
buffer.setLength(Int64.Max + 1)
} catch (e: OverflowException) {
println("Error: " + e.message)
}
/* When you try to set the length to –1, an exception is thrown. */
try {
buffer.setLength(-1)
} catch (e: IllegalArgumentException) {
println("Error: " + e.message)
}
}
Results:
initial length: 11
set length to 5: Hello
Error: add
Error: The length must be greater than or equal to 0.
func write(Array<Byte>)
public func write(buffer: Array<Byte>): Unit
Description: Writes data in buffer to the output stream.
Parameters:
Examples:
import std.io.ByteBuffer
main(): Unit {
let buffer = ByteBuffer()
let dataToWrite = "Hello World".toArray()
/* Write data. */
buffer.write(dataToWrite)
println(String.fromUtf8(buffer.bytes()))
}
Results:
Hello World
func writeByte(Byte)
public func writeByte(v: Byte): Unit
Description: Writes a byte to the output stream.
Parameters:
- v: Byte: byte to be written
Examples:
import std.io.ByteBuffer
main(): Unit {
let buffer = ByteBuffer()
let dataToWrite : Array<Byte> = "Hello World".toArray()
/* Write a single byte each time. */
for( i in 0 .. dataToWrite.size){
buffer.writeByte(dataToWrite[i])
}
println(String.fromUtf8(buffer.bytes()))
}
Results:
Hello World
class ChainedInputStream<T> where T <: InputStream
public class ChainedInputStream<T> <: InputStream where T <: InputStream {
public init(input: Array<T>)
}
Description: Reads data from the InputStream array in sequence.
Parent types:
init(Array<T>)
public init(input: Array<T>)
Description: Creates a ChainedInputStream instance.
Parameters:
- input: Array<T>: bound input stream array
Throws:
- IllegalArgumentException: If input is empty, this exception is thrown.
func read(Array<Byte>)
public func read(buffer: Array<Byte>): Int64
Description: Reads data from the bound InputStream array and writes the data to buffer in sequence.
Parameters:
Returns:
- Int64: number of bytes read
Throws:
- IllegalArgumentException: If buffer is empty, this exception is thrown.
Examples:
import std.io.*
main(): Unit {
let inputData = "Hello World".toArray()
let bufferInput = ByteBuffer(inputData)
let cis = ChainedInputStream(bufferInput)
// The buffer capacity is 7.
let bufferOutput = Array<Byte>(7, repeat: 0)
cis.read(bufferOutput)
let result = String.fromUtf8(bufferOutput)
println(result)
}
Results:
Hello W
class MultiOutputStream<T> where T <: OutputStream
public class MultiOutputStream<T> <: OutputStream where T <: OutputStream {
public init(output: Array<T>)
}
Description: Writes data to each output stream in the OutputStream array at the same time.
Parent types:
init(Array<T>)
public init(output: Array<T>)
Description: Creates a MultiOutputStream instance.
Parameters:
- output: Array<T>: bound output stream array
Throws:
- IllegalArgumentException: If output is empty, this exception is thrown.
func flush()
public func flush(): Unit
Description: Refreshes each output stream in the bound output stream array.
func write(Array<Byte>)
public func write(buffer: Array<Byte>): Unit
Description: Writes the value of buffer to each output stream in the bound OutputStream array.
Parameters:
class StringReader<T> where T <: InputStream
public class StringReader<T> where T <: InputStream {
public init(input: T)
}
Description: Reads data from the InputStream input stream and converts the data to characters or a string.
NOTE
- By default, StringReader has a buffer with a size of 4096 bytes.
- Currently, StringReader supports only UTF-8 encoding.
init(T)
public init(input: T)
Description: Creates a StringReader instance.
Parameters:
- input: T: input stream from which the data to be read
func lines()
public func lines(): Iterator<String>
Description: Obtains the line iterator of StringReader.
It is equivalent to cyclically calling func readln(). If there is an invalid character, an exception is thrown.
NOTE
- Each line ends with a newline character.
- The newline character can be
\n,\r, or\r\n.- The read line string does not contain the newline character at the end.
Returns:
Throws:
- ContentFormatException: If the
for-insyntax is used to traverse the iterator or an invalid character is read when thenext()method is called, this exception is thrown.
func read()
public func read(): ?Rune
Description: Reads data in a stream by character.
Returns:
- ?Rune: If data is read successfully, Option<Rune>.Some(c) is returned, where c is the character read. Otherwise, Option<Rune>.None is returned.
Throws:
- ContentFormatException: If an invalid character is read, this exception is thrown.
func readToEnd()
public func readToEnd(): String
Description: Reads the remaining data in a stream.
Returns:
- String: remaining data in the stream
Throws:
- ContentFormatException: If an invalid character is read, this exception is thrown.
func readUntil((Rune)->Bool)
public func readUntil(predicate: (Rune)->Bool): Option<String>
Description: Reads data in a stream to the character position (including the character) that makes predicate return true or to the end of the stream.
Parameters:
- predicate: (Rune)->Bool: expression for returning true under certain conditions
Returns:
- Option<String>: If data is read successfully, Option<String>.Some(str) is returned, where str is the string read. Otherwise, Option<String>.None is returned.
Throws:
- ContentFormatException: If an invalid character is read, this exception is thrown.
func readUntil(Rune)
public func readUntil(v: Rune): Option<String>
Description: Reads data in a stream to a specified character (including the character) or to the end of the stream.
Parameters:
- v: Rune: the specified character
Returns:
- Option<String>: If data is read successfully, Option<String>.Some(str) is returned, where str is the string read. Otherwise, Option<String>.None is returned.
Throws:
- ContentFormatException: If an invalid character is read, this exception is thrown.
func readln()
public func readln(): Option<String>
Description: Reads data in a stream by row.
NOTE
- The original newline characters are removed from the read data.
Returns:
- Option<String>: If data is read successfully, Option<String>.Some(str) is returned, where str is the string read. Otherwise, Option<String>.None is returned.
Throws:
- ContentFormatException: If an invalid character is read, this exception is thrown.
func runes()
public func runes(): Iterator<Rune>
Description: Obtains the Rune iterator of StringReader.
Returns:
Throws:
- ContentFormatException: If an invalid character is read when
for-inornext()is called, this exception is thrown.
extend<T> StringReader<T> <: Resource where T <: Resource
extend<T> StringReader<T> <: Resource where T <: Resource
Description: Implements the Resource interface for StringReader. This type of object can implement automatic resource release in the try-with-resource syntax context.
Parent types:
func close()
public func close(): Unit
Description: Closes the current stream.
NOTE
- After this method is called, other interfaces of StringReader cannot be called. Otherwise, unexpected problems may occur.
func isClosed()
public func isClosed(): Bool
Description: Checks whether the current stream is closed.
Returns:
- Bool: true: yes, false: no
extend<T> StringReader<T> <: Seekable where T <: Seekable
extend<T> StringReader<T> <: Seekable where T <: Seekable
Description: Implements the Seekable interface for StringReader to implement operations such as querying data length and moving the cursor.
Parent types:
prop position
public prop position: Int64
Description: Returns the current cursor position.
Type: Int64
func seek(SeekPosition)
public func seek(sp: SeekPosition): Int64
Description: Moves the cursor to a specified position.
NOTE
- The specified position cannot be before the data header in the stream.
- The specified position can be after the end of the data in the stream.
Parameters:
- sp: SeekPosition: the position to which the cursor is to be moved
Returns:
- Int64: the offset (in bytes) from the start point of the data in the stream to the position after the cursor is moved
Throws:
- IOException: If the specified position is before the data header in the stream, this exception is thrown.
class StringWriter<T> where T <: OutputStream
public class StringWriter<T> where T <: OutputStream {
public init(output: T)
}
Description: Converts String and some ToString types to strings in the specified encoding format and byte order and writes the strings to the output stream.
NOTE
- By default, StringWriter has a buffer with a size of 4096 bytes.
- Currently, StringWriter supports only UTF-8 encoding.
init(T)
public init(output: T)
Description: Creates a StringWriter instance.
Parameters:
- output: T: output stream to which data is to be written
func flush()
public func flush(): Unit
Description: Refreshes the internal buffer, writes the data in the buffer to output, and refreshes output.
func write(Bool)
public func write(v: Bool): Unit
Description: Writes the Bool type.
Parameters:
func write(Float16)
public func write(v: Float16): Unit
Description: Writes the Float16 type.
Parameters:
func write(Float32)
public func write(v: Float32): Unit
Description: Writes the Float32 type.
Parameters:
func write(Float64)
public func write(v: Float64): Unit
Description: Writes the Float64 type.
Parameters:
func write(Int16)
public func write(v: Int16): Unit
Description: Writes the Int16 type.
Parameters:
func write(Int32)
public func write(v: Int32): Unit
Description: Writes the Int32 type.
Parameters:
func write(Int64)
public func write(v: Int64): Unit
Description: Writes the Int64 type.
Parameters:
func write(Int8)
public func write(v: Int8): Unit
Description: Writes the Int8 type.
Parameters:
func write(Rune)
public func write(v: Rune): Unit
Description: Writes the Rune type.
Parameters:
func write(String)
public func write(v: String): Unit
Description: Writes a string.
Parameters:
- v: String: string to be written
func write(UInt16)
public func write(v: UInt16): Unit
Description: Writes the UInt16 type.
Parameters:
func write(UInt32)
public func write(v: UInt32): Unit
Description: Writes the UInt32 type.
Parameters:
func write(UInt64)
public func write(v: UInt64): Unit
Description: Writes the UInt64 type.
Parameters:
func write(UInt8)
public func write(v: UInt8): Unit
Description: Writes the UInt8 type.
Parameters:
func write<T>(T) where T <: ToString
public func write<T>(v: T): Unit where T <: ToString
Description: Writes the ToString type.
Parameters:
- v: T: instance of the ToString type
func writeln()
public func writeln(): Unit
Description: Writes a newline character.
func writeln(Bool)
public func writeln(v: Bool): Unit
Description: Writes the Bool type and newline characters.
Parameters:
func writeln(Float16)
public func writeln(v: Float16): Unit
Description: Writes the Float16 type and newline characters.
Parameters:
func writeln(Float32)
public func writeln(v: Float32): Unit
Description: Writes the Float32 type and newline characters.
Parameters:
func writeln(Float64)
public func writeln(v: Float64): Unit
Description: Writes the Float64 type and newline characters.
Parameters:
func writeln(Int16)
public func writeln(v: Int16): Unit
Description: Writes the Int16 type and newline characters.
Parameters:
func writeln(Int32)
public func writeln(v: Int32): Unit
Description: Writes the Int32 type and newline characters.
Parameters:
func writeln(Int64)
public func writeln(v: Int64): Unit
Description: Writes the Int64 type and newline characters.
Parameters:
func writeln(Int8)
public func writeln(v: Int8): Unit
Description: Writes the Int8 type and newline characters.
Parameters:
func writeln(Rune)
public func writeln(v: Rune): Unit
Description: Writes the Rune type and newline characters.
Parameters:
func writeln(String)
public func writeln(v: String): Unit
Description: Writes a string and a newline character.
Parameters:
- v: String: string to be written
func writeln(UInt16)
public func writeln(v: UInt16): Unit
Description: Writes the UInt16 type and newline characters.
Parameters:
func writeln(UInt32)
public func writeln(v: UInt32): Unit
Description: Writes the UInt32 type and newline characters.
Parameters:
func writeln(UInt64)
public func writeln(v: UInt64): Unit
Description: Writes the UInt64 type and newline characters.
Parameters:
func writeln(UInt8)
public func writeln(v: UInt8): Unit
Description: Writes the UInt8 type and newline characters.
Parameters:
func writeln<T>(T) where T <: ToString
public func writeln<T>(v: T): Unit where T <: ToString
Description: Writes the ToString type and newline characters.
Parameters:
- v: T: instance of the ToString type
extend<T> StringWriter<T> <: Resource where T <: Resource
extend<T> StringWriter<T> <: Resource where T <: Resource
Description: Implements the Resource interface for StringWriter. This type of object can implement automatic resource release in the try-with-resource syntax context.
Parent types:
func close()
public func close(): Unit
Description: Closes the current stream.
NOTE
- After this method is called, other interfaces of StringWriter cannot be called. Otherwise, unexpected problems may occur.
func isClosed()
public func isClosed(): Bool
Description: Checks whether the current stream is closed.
Returns:
- Bool: true: yes, false: no
extend<T> StringWriter<T> <: Seekable where T <: Seekable
extend<T> StringWriter<T> <: Seekable where T <: Seekable
Description: Implements the Seekable interface for StringWriter to implement operations such as querying data length and moving the cursor.
Parent types:
func seek(SeekPosition)
public func seek(sp: SeekPosition): Int64
Description: Moves the cursor to a specified position.
NOTE
- The specified position cannot be before the data header in the stream.
- The specified position can be after the end of the data in the stream.
Parameters:
- sp: SeekPosition: the position to which the cursor is to be moved
Returns:
- Int64: the offset (in bytes) from the start point of the data in the stream to the position after the cursor is moved
Throws:
- IOException: If the specified position is before the data header in the stream, this exception is thrown.