0
# I/O & Networking
1
2
Network address handling, file channel operations, and stream adapters for efficient I/O. Provides comprehensive utilities for network communication, file operations, and stream processing with JVM-specific optimizations.
3
4
## Capabilities
5
6
### Network Address Handling
7
8
Classes and utilities for working with network addresses and endpoints.
9
10
```kotlin { .api }
11
/**
12
* Represents a network address with hostname and port
13
* On JVM, this is a typealias to java.net.SocketAddress
14
*/
15
typealias NetworkAddress = java.net.SocketAddress
16
17
/**
18
* Create a NetworkAddress with hostname and port
19
* @param hostname Host name or IP address
20
* @param port Port number
21
* @return NetworkAddress instance (InetSocketAddress on JVM)
22
*/
23
fun NetworkAddress(hostname: String, port: Int): NetworkAddress
24
25
/**
26
* Get hostname from NetworkAddress
27
*/
28
val NetworkAddress.hostname: String
29
30
/**
31
* Get IP address string from NetworkAddress
32
*/
33
val NetworkAddress.address: String
34
35
/**
36
* Get port from NetworkAddress
37
*/
38
val NetworkAddress.port: Int
39
}
40
```
41
42
**Usage Examples:**
43
44
```kotlin
45
import io.ktor.util.network.*
46
47
// Create network addresses
48
val localhost = NetworkAddress("localhost", 8080)
49
val remote = NetworkAddress("api.example.com", 443)
50
51
println(localhost) // "localhost:8080"
52
53
// Use in network operations
54
fun connectTo(address: NetworkAddress) {
55
println("Connecting to ${address.hostname}:${address.port}")
56
}
57
58
connectTo(localhost)
59
```
60
61
### File Channel Operations
62
63
JVM-specific utilities for efficient file I/O using NIO channels.
64
65
```kotlin { .api }
66
/**
67
* Create a read channel from a File
68
* @return ByteReadChannel for reading file content
69
*/
70
fun File.readChannel(): ByteReadChannel
71
72
/**
73
* Create a write channel to a File
74
* @param append Whether to append to existing file or overwrite
75
* @return ByteWriteChannel for writing file content
76
*/
77
fun File.writeChannel(append: Boolean = false): ByteWriteChannel
78
79
/**
80
* Read channel from file at NIO Path
81
* @return ByteReadChannel for reading
82
*/
83
fun java.nio.file.Path.readChannel(): ByteReadChannel
84
85
/**
86
* Write channel to file at NIO Path
87
* @param append Whether to append to existing content
88
* @return ByteWriteChannel for writing
89
*/
90
fun java.nio.file.Path.writeChannel(append: Boolean = false): ByteWriteChannel
91
```
92
93
**Usage Examples:**
94
95
```kotlin
96
import io.ktor.util.cio.*
97
import java.io.File
98
import java.nio.file.Paths
99
100
// File-based I/O
101
val file = File("data.txt")
102
103
// Read from file
104
val readChannel = file.readChannel()
105
val content = readChannel.readRemaining().readText()
106
println(content)
107
108
// Write to file
109
val writeChannel = file.writeChannel()
110
writeChannel.writeStringUtf8("Hello, World!")
111
writeChannel.close()
112
113
// Append to file
114
val appendChannel = file.writeChannel(append = true)
115
appendChannel.writeStringUtf8("\nAppended content")
116
appendChannel.close()
117
118
// NIO Path operations
119
val path = Paths.get("data.txt")
120
val pathReadChannel = path.readChannel()
121
val pathWriteChannel = path.writeChannel()
122
```
123
124
### Stream Adapters
125
126
Convert between Ktor channels and standard Java I/O streams.
127
128
```kotlin { .api }
129
/**
130
* Convert ByteReadChannel to InputStream
131
* @return InputStream that reads from the channel
132
*/
133
fun ByteReadChannel.toInputStream(): InputStream
134
135
/**
136
* Convert ByteWriteChannel to OutputStream
137
* @return OutputStream that writes to the channel
138
*/
139
fun ByteWriteChannel.toOutputStream(): OutputStream
140
141
/**
142
* Convert InputStream to ByteReadChannel
143
* @param pool ByteBuffer pool for efficient memory usage
144
* @return ByteReadChannel that reads from the stream
145
*/
146
fun InputStream.toByteReadChannel(
147
pool: ObjectPool<ByteBuffer> = ByteBufferPool
148
): ByteReadChannel
149
150
/**
151
* Convert OutputStream to ByteWriteChannel
152
* @param pool ByteBuffer pool for efficient memory usage
153
* @return ByteWriteChannel that writes to the stream
154
*/
155
fun OutputStream.toByteWriteChannel(
156
pool: ObjectPool<ByteBuffer> = ByteBufferPool
157
): ByteWriteChannel
158
```
159
160
**Usage Examples:**
161
162
```kotlin
163
import io.ktor.util.cio.*
164
import java.io.*
165
166
// Convert channel to stream for legacy APIs
167
val readChannel: ByteReadChannel = // ... from somewhere
168
val inputStream = readChannel.toInputStream()
169
170
// Use with standard Java APIs
171
val bufferedReader = BufferedReader(InputStreamReader(inputStream))
172
val line = bufferedReader.readLine()
173
174
// Convert stream to channel
175
val fileInputStream = FileInputStream("data.txt")
176
val channelFromStream = fileInputStream.toByteReadChannel()
177
178
// Write channel to stream
179
val writeChannel: ByteWriteChannel = // ...
180
val outputStream = writeChannel.toOutputStream()
181
val printWriter = PrintWriter(outputStream)
182
printWriter.println("Hello from stream")
183
printWriter.flush()
184
```
185
186
### NIO Channel Operations
187
188
Low-level NIO channel utilities for advanced I/O operations.
189
190
```kotlin { .api }
191
/**
192
* Create ByteReadChannel from ReadableByteChannel
193
* @return ByteReadChannel that reads from NIO channel
194
*/
195
fun ReadableByteChannel.readChannel(): ByteReadChannel
196
197
/**
198
* Create ByteWriteChannel from WritableByteChannel
199
* @return ByteWriteChannel that writes to NIO channel
200
*/
201
fun WritableByteChannel.writeChannel(): ByteWriteChannel
202
203
/**
204
* Create ByteReadChannel from FileChannel
205
* @param start Starting position in the file
206
* @param endInclusive Ending position in the file (inclusive)
207
* @return ByteReadChannel for reading file range
208
*/
209
fun FileChannel.readChannel(
210
start: Long = 0,
211
endInclusive: Long = -1
212
): ByteReadChannel
213
214
/**
215
* Create ByteWriteChannel from FileChannel
216
* @param start Starting position for writing
217
* @return ByteWriteChannel for writing to file
218
*/
219
fun FileChannel.writeChannel(start: Long = 0): ByteWriteChannel
220
```
221
222
**Usage Examples:**
223
224
```kotlin
225
import io.ktor.util.*
226
import java.nio.channels.*
227
import java.io.RandomAccessFile
228
229
// Work with file channels directly
230
val randomAccessFile = RandomAccessFile("data.bin", "rw")
231
val fileChannel = randomAccessFile.channel
232
233
// Read from specific range
234
val rangeChannel = fileChannel.readChannel(start = 100, endInclusive = 199)
235
val data = rangeChannel.readRemaining()
236
237
// Write to specific position
238
val writeChannel = fileChannel.writeChannel(start = 50)
239
writeChannel.writeFully(data)
240
241
// Work with socket channels
242
val socketChannel = SocketChannel.open()
243
val readChannel = socketChannel.readChannel()
244
val writeChannel = socketChannel.writeChannel()
245
```
246
247
### ByteBuffer Pool
248
249
Memory pool for efficient ByteBuffer reuse in I/O operations.
250
251
```kotlin { .api }
252
/**
253
* Object pool for ByteBuffer instances to reduce garbage collection
254
*/
255
object ByteBufferPool {
256
/** Borrow a ByteBuffer from the pool */
257
fun borrow(): ByteBuffer
258
259
/** Return a ByteBuffer to the pool */
260
fun recycle(buffer: ByteBuffer)
261
262
/** Get pool capacity */
263
val capacity: Int
264
}
265
266
/**
267
* Generic object pool interface
268
*/
269
interface ObjectPool<T> {
270
/** Borrow an object from the pool */
271
fun borrow(): T
272
273
/** Return an object to the pool */
274
fun recycle(instance: T)
275
276
/** Dispose of the pool */
277
fun dispose()
278
}
279
```
280
281
**Usage Examples:**
282
283
```kotlin
284
import io.ktor.util.cio.*
285
286
// Use ByteBuffer pool for efficient memory management
287
val buffer = ByteBufferPool.borrow()
288
try {
289
// Use buffer for I/O operations
290
buffer.clear()
291
// ... read/write operations
292
} finally {
293
ByteBufferPool.recycle(buffer)
294
}
295
296
// Pool is used automatically by stream adapters
297
val inputStream = FileInputStream("large-file.dat")
298
val channel = inputStream.toByteReadChannel(pool = ByteBufferPool)
299
```
300
301
### Channel Utilities
302
303
Additional utilities for working with byte channels.
304
305
```kotlin { .api }
306
/**
307
* Copy all data from source channel to destination channel
308
* @param dst Destination channel
309
* @return Number of bytes copied
310
*/
311
suspend fun ByteReadChannel.copyTo(dst: ByteWriteChannel): Long
312
313
/**
314
* Copy data with progress callback
315
* @param dst Destination channel
316
* @param progressCallback Called periodically with bytes copied
317
* @return Total bytes copied
318
*/
319
suspend fun ByteReadChannel.copyTo(
320
dst: ByteWriteChannel,
321
progressCallback: (Long) -> Unit
322
): Long
323
324
/**
325
* Read all remaining data as ByteArray
326
* @return All remaining bytes
327
*/
328
suspend fun ByteReadChannel.readRemaining(): ByteArray
329
330
/**
331
* Read all remaining data as String with specified charset
332
* @param charset Character encoding (default UTF-8)
333
* @return Decoded string
334
*/
335
suspend fun ByteReadChannel.readUTF8Line(): String?
336
```
337
338
**Usage Examples:**
339
340
```kotlin
341
import io.ktor.util.cio.*
342
343
// Copy between channels with progress
344
val sourceFile = File("source.dat")
345
val destFile = File("destination.dat")
346
347
val source = sourceFile.readChannel()
348
val destination = destFile.writeChannel()
349
350
val totalBytes = source.copyTo(destination) { bytesCopied ->
351
println("Copied $bytesCopied bytes")
352
}
353
354
println("Total copied: $totalBytes bytes")
355
356
// Read content as string
357
val textFile = File("readme.txt")
358
val textChannel = textFile.readChannel()
359
val content = textChannel.readRemaining().decodeToString()
360
println(content)
361
```
362
363
### Path Utilities
364
365
JVM-specific path manipulation utilities.
366
367
```kotlin { .api }
368
/**
369
* Convert string to Path
370
* @return NIO Path instance
371
*/
372
fun String.toPath(): java.nio.file.Path
373
374
/**
375
* Get file extension from Path
376
*/
377
val java.nio.file.Path.extension: String
378
379
/**
380
* Get file name without extension
381
*/
382
val java.nio.file.Path.nameWithoutExtension: String
383
384
/**
385
* Check if path represents a hidden file
386
*/
387
val java.nio.file.Path.isHidden: Boolean
388
```
389
390
**Usage Examples:**
391
392
```kotlin
393
import io.ktor.util.*
394
import java.nio.file.Paths
395
396
// Path manipulation
397
val pathString = "/home/user/document.pdf"
398
val path = pathString.toPath()
399
400
println(path.extension) // "pdf"
401
println(path.nameWithoutExtension) // "document"
402
println(path.isHidden) // false
403
404
// Work with different path types
405
val relativePath = "configs/app.properties".toPath()
406
val absolutePath = "/etc/hostname".toPath()
407
408
// Use with file operations
409
val configChannel = relativePath.readChannel()
410
val systemChannel = absolutePath.readChannel()
411
```