Skip to content

Commit 51ea7fd

Browse files
authored
[KTLN-702] Add Samples (#773)
* [KTLN-702] Add Samples * [KTLN-702] Add Samples
1 parent 56e89f6 commit 51ea7fd

File tree

1 file changed

+43
-0
lines changed
  • core-kotlin-modules/core-kotlin-files/src/main/kotlin/com/baeldung/bytearray

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.baeldung.bytearray
2+
3+
import java.io.BufferedOutputStream
4+
import java.io.File
5+
import java.io.FileOutputStream
6+
import java.io.IOException
7+
8+
fun fileToByteArray(filePath: String): ByteArray {
9+
val file = File(filePath)
10+
return file.readBytes()
11+
}
12+
13+
14+
fun readFileUsingReader(filePath: String): ByteArray {
15+
val file = File(filePath)
16+
val contentBuilder = StringBuilder()
17+
18+
file.reader().use { reader ->
19+
reader.forEachLine { line ->
20+
contentBuilder.append(line).append("\n")
21+
}
22+
}
23+
24+
return contentBuilder.toString().toByteArray()
25+
}
26+
27+
fun largeFileToByteArray(filePath: String, outputFilePath: String) {
28+
File(filePath).bufferedReader().use { reader ->
29+
BufferedOutputStream(FileOutputStream(outputFilePath)).use { bufferOut ->
30+
reader.lineSequence()
31+
.forEach { line -> bufferOut.write(line.toByteArray()) }
32+
}
33+
}
34+
}
35+
36+
fun safeFileToByteArray(filePath: String): ByteArray? {
37+
return try {
38+
File(filePath).readBytes()
39+
} catch (e: IOException) {
40+
println("Error reading file: ${e.message}")
41+
null
42+
}
43+
}

0 commit comments

Comments
 (0)