File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
core-kotlin-modules/core-kotlin-files/src/main/kotlin/com/baeldung/bytearray Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments