在Kotlin中,你可以使用java.io
和java.nio.file
包中的类和方法来执行文件操作。以下是一些常见的文件操作示例:
- 创建目录:
import java.io.File fun main() { val directoryPath = "path/to/directory" val directory = File(directoryPath) if (!directory.exists()) { directory.mkdir() } }
- 创建文件:
import java.io.File import java.io.IOException fun main() { val filePath = "path/to/file.txt" val file = File(filePath) if (!file.exists()) { try { file.createNewFile() } catch (e: IOException) { println("Error creating file: ${e.message}") } } }
- 读取文件内容:
import java.io.File import java.io.FileReader fun main() { val filePath = "path/to/file.txt" val file = File(filePath) if (file.exists()) { val reader = FileReader(file) try { val content = reader.readText() println(content) } finally { reader.close() } } else { println("File not found") } }
- 写入文件内容:
import java.io.File import java.io.FileWriter import java.io.IOException fun main() { val filePath = "path/to/file.txt" val file = File(filePath) val content = "Hello, World!" if (!file.exists()) { try { file.createNewFile() } catch (e: IOException) { println("Error creating file: ${e.message}") } } try { val writer = FileWriter(file) writer.write(content) writer.close() } catch (e: IOException) { println("Error writing to file: ${e.message}") } }
- 遍历目录:
import java.io.File fun main() { val directoryPath = "path/to/directory" val directory = File(directoryPath) if (directory.exists() && directory.isDirectory) { for (child in directory.listFiles() ?: emptyArray()) { println("File: ${child.name}") if (child.isDirectory) { println("Directory: ${child.name}") } } } else { println("Directory not found") } }
这些示例展示了如何在Kotlin中执行基本的文件操作。你可以根据需要调整这些示例以满足你的需求。