English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to convert a File object to a byte [] and a byte [] to a File object in Kotlin.
Before converting the file to a byte array, we assume that insrcThere is a folder namedtest.txtfile.
This is thetest.txtcontent
This is the Test file.
import java.io.IOException import java.nio.file.Files import java.nio.file.Paths import java.util.Arrays fun main(args: Array<String>) { val path = System.getProperty("user.dir") + "\\src\\test.txt" try { val encoded = Files.readAllBytes(Paths.get(path)) println(Arrays.toString(encoded)) catch (e: IOException) { } }
When running the program, the output is:
[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]
In the above program, we store the file path in the variable path.
Then, in the try block, we use the readAllBytes() method to read all bytes from the given path.
Then, we use the Arrays.toString() method to print the byte array.
Since the readAllBytes() method may throw IOException, we use try in our program-catch block.
import java.io.IOException import java.nio.file.Files import java.nio.file.Paths fun main(args: Array<String>) { val path = System.getProperty("user.dir") + "\\src\\test.txt" val finalPath = System.getProperty("user.dir") + "\\src\\final.txt" try { val encoded = Files.readAllBytes(Paths.get(path)) Files.write(Paths.get(finalPath), encoded) catch (e: IOException) { } }
When running the program,test.txtThe content will be copied tofinal.txt.
In the above program, we used the same method as in the example1The same method can be used to read all bytes from the File stored at path. These bytes are stored in the array encoded.
We also have a finalPath for writing bytes.
Then, we just need to use the Files' write() method to write the encoded byte array into the file at the given finalPath.
This is the equivalent Java code:Java Program to Convert File to byte [], and vice versa.