0
# Okio
1
2
Okio is a modern I/O library that complements java.io and java.nio to make it much easier to access, store, and process your data. Originally developed as a component of OkHttp, Okio provides efficient implementations of core I/O primitives including ByteString (immutable byte sequences), Buffer (mutable byte queues), Source (input streams), and Sink (output streams) that work consistently across JVM, Android, JavaScript, and native platforms.
3
4
## Package Information
5
6
- **Package Name**: okio-jvm
7
- **Package Type**: maven
8
- **Language**: Kotlin (with Java interop)
9
- **Installation**: `implementation 'com.squareup.okio:okio-jvm:3.12.0'`
10
11
## Core Imports
12
13
Kotlin:
14
15
```kotlin
16
import okio.*
17
```
18
19
Or import specific classes:
20
21
```kotlin
22
import okio.Buffer
23
import okio.ByteString
24
import okio.FileSystem
25
import okio.Path
26
import okio.Source
27
import okio.Sink
28
```
29
30
Java:
31
32
```java
33
import okio.Buffer;
34
import okio.ByteString;
35
import okio.FileSystem;
36
import okio.Okio;
37
import okio.Source;
38
import okio.Sink;
39
```
40
41
## Basic Usage
42
43
```kotlin
44
import okio.*
45
46
// Working with ByteString (immutable bytes)
47
val bytes = "Hello, Okio!".encodeUtf8()
48
println(bytes.hex()) // Hexadecimal representation
49
println(bytes.base64()) // Base64 encoding
50
51
// Working with Buffer (mutable bytes)
52
val buffer = Buffer()
53
buffer.writeUtf8("Hello")
54
buffer.writeUtf8(", ")
55
buffer.writeUtf8("World!")
56
println(buffer.readUtf8()) // "Hello, World!"
57
58
// Reading and writing files
59
val path = "/tmp/example.txt".toPath()
60
FileSystem.SYSTEM.write(path) {
61
writeUtf8("File content")
62
}
63
val content = FileSystem.SYSTEM.read(path) {
64
readUtf8()
65
}
66
67
// Streaming I/O
68
val source: Source = path.source()
69
val bufferedSource = source.buffer()
70
val line = bufferedSource.readUtf8Line()
71
bufferedSource.close()
72
```
73
74
## Architecture
75
76
Okio is built around several key components:
77
78
- **ByteString**: Immutable byte sequences with encoding utilities (UTF-8, Base64, Hex)
79
- **Buffer**: Mutable byte collections with efficient segment-based storage
80
- **Source/Sink**: Streaming I/O abstractions similar to InputStream/OutputStream but simpler
81
- **BufferedSource/BufferedSink**: Buffered variants with convenient methods for reading/writing data types
82
- **FileSystem**: Cross-platform file system access with Path abstraction
83
- **Timeout**: Timeout policies for I/O operations
84
85
The library emphasizes memory efficiency through features like segment pooling for buffers, copy-on-write semantics for ByteString, and built-in support for various data formats.
86
87
## Capabilities
88
89
### ByteString Operations
90
91
Immutable byte sequences with encoding, hashing, and manipulation utilities. Ideal for working with binary data, API keys, and data that needs to be shared across threads.
92
93
```kotlin { .api }
94
abstract class ByteString : Comparable<ByteString> {
95
abstract val size: Int
96
abstract fun utf8(): String
97
abstract fun base64(): String
98
abstract fun hex(): String
99
abstract fun sha256(): ByteString
100
abstract fun toByteArray(): ByteArray
101
}
102
103
companion object {
104
val EMPTY: ByteString
105
fun of(vararg data: Byte): ByteString
106
}
107
108
fun String.encodeUtf8(): ByteString
109
fun ByteArray.toByteString(offset: Int = 0, byteCount: Int = size): ByteString
110
```
111
112
[ByteString Operations](./bytestring.md)
113
114
### Buffer Operations
115
116
Mutable byte collections with efficient operations for building and manipulating byte sequences. Perfect for parsing protocols, building requests, and streaming data processing.
117
118
```kotlin { .api }
119
class Buffer : BufferedSource, BufferedSink {
120
val size: Long
121
fun clear()
122
fun copy(): Buffer
123
fun snapshot(): ByteString
124
fun get(pos: Long): Byte
125
}
126
```
127
128
[Buffer Operations](./buffer.md)
129
130
### Source and Sink Streaming
131
132
Streaming I/O abstractions for reading and writing bytes with timeout support and efficient buffering.
133
134
```kotlin { .api }
135
interface Source : Closeable {
136
fun read(sink: Buffer, byteCount: Long): Long
137
fun timeout(): Timeout
138
}
139
140
interface Sink : Closeable {
141
fun write(source: Buffer, byteCount: Long)
142
fun flush()
143
fun timeout(): Timeout
144
}
145
146
interface BufferedSource : Source {
147
val buffer: Buffer
148
fun readUtf8(): String
149
fun readByte(): Byte
150
fun readInt(): Int
151
fun readLong(): Long
152
}
153
154
interface BufferedSink : Sink {
155
val buffer: Buffer
156
fun writeUtf8(string: String): BufferedSink
157
fun writeByte(b: Int): BufferedSink
158
fun writeInt(i: Int): BufferedSink
159
fun writeLong(v: Long): BufferedSink
160
}
161
```
162
163
[Source and Sink Streaming](./sources-sinks.md)
164
165
### File System Operations
166
167
Cross-platform file system access with path manipulation, metadata queries, and efficient file I/O operations.
168
169
```kotlin { .api }
170
abstract class FileSystem : Closeable {
171
abstract fun canonicalize(path: Path): Path
172
abstract fun list(dir: Path): List<Path>
173
abstract fun source(file: Path): Source
174
abstract fun sink(file: Path, mustCreate: Boolean = false): Sink
175
abstract fun createDirectory(dir: Path, mustCreate: Boolean = false)
176
abstract fun delete(path: Path, mustExist: Boolean = true)
177
178
companion object {
179
val SYSTEM: FileSystem
180
val SYSTEM_TEMPORARY_DIRECTORY: Path
181
}
182
}
183
184
class Path : Comparable<Path> {
185
val name: String
186
val parent: Path?
187
val isAbsolute: Boolean
188
operator fun div(child: String): Path
189
}
190
191
fun String.toPath(normalize: Boolean = false): Path
192
```
193
194
[File System Operations](./filesystem.md)
195
196
### Hash and Cryptographic Operations
197
198
Built-in hashing and cryptographic operations for data integrity and security.
199
200
```kotlin { .api }
201
// ByteString hashing methods
202
fun ByteString.sha1(): ByteString
203
fun ByteString.sha256(): ByteString
204
fun ByteString.sha512(): ByteString
205
fun ByteString.hmacSha256(key: ByteString): ByteString
206
207
// Streaming hash computation
208
class HashingSink(sink: Sink, algorithm: String) : Sink {
209
val hash: ByteString
210
}
211
212
class HashingSource(source: Source, algorithm: String) : Source {
213
val hash: ByteString
214
}
215
```
216
217
[Hash and Cryptographic Operations](./hashing.md)
218
219
### Platform-Specific Extensions
220
221
JVM-specific extensions for interoperability with Java I/O, NIO, and security APIs.
222
223
```kotlin { .api }
224
// Java I/O extensions
225
fun OutputStream.sink(): Sink
226
fun InputStream.source(): Source
227
fun File.source(): Source
228
fun File.sink(append: Boolean = false): Sink
229
230
// Security extensions
231
fun Sink.cipherSink(cipher: Cipher): CipherSink
232
fun Source.cipherSource(cipher: Cipher): CipherSource
233
234
// Async operations
235
class AsyncTimeout : Timeout {
236
fun enter()
237
fun exit(): Boolean
238
fun <T> withTimeout(block: () -> T): T
239
}
240
```
241
242
[JVM Extensions](./jvm-extensions.md)
243
244
## Types
245
246
### Core Types
247
248
```kotlin { .api }
249
interface Closeable {
250
fun close()
251
}
252
253
abstract class Timeout {
254
open fun timeoutNanos(): Long
255
open fun hasDeadline(): Boolean
256
open fun deadlineNanoTime(): Long
257
258
companion object {
259
val NONE: Timeout
260
}
261
}
262
263
data class FileMetadata(
264
val isRegularFile: Boolean,
265
val isDirectory: Boolean,
266
val symlinkTarget: Path?,
267
val size: Long?,
268
val createdAtMillis: Long?,
269
val lastModifiedAtMillis: Long?,
270
val lastAccessedAtMillis: Long?
271
)
272
```
273
274
### Exception Types
275
276
```kotlin { .api }
277
class EOFException(message: String? = null) : IOException(message)
278
```