English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Recopilación de ejemplos de Kotlin
在此程序中,您将学习在Kotlin中将File对象转换为byte [],byte []转换为File对象。
在将文件转换为字节数组之前,我们假设在src文件夹中有一个名为test.txt的文件。
这是test.txt的内容
This is a 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) { } }
运行该程序时,输出为:
[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]
在上面的程序中,我们将文件的路径存储在变量 path 中。
然后,在try块中,我们使用readAllBytes()方法从给定的path读取所有字节。
然后,我们使用Arrays的 toString()方法来打印字节数组。
由于readAllBytes()方法可能会抛出IOException,因此我们在程序中使用了 try-catch 块。
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) { } }
Al ejecutar el programatest.txtEl contenido se copiará enfinal.txt。
En el programa anterior, usamos el ejemplo1Mismo método para leer todos los bytes del File almacenado en path. Estos bytes se almacenan en el array encoded.
Tenemos otro finalPath para escribir bytes.
Luego, solo necesitamos usar el método write() de Files para escribir el array de bytes codificados en el archivo en el finalPath dado.
Este es el código Java equivalente:Java programa que convierte File a byte [] y viceversa。