在Kotlin中,你可以使用java.io
和java.nio.file
包中的類和方法來執(zhí)行文件操作。以下是一些常見的文件操作示例:
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中執(zhí)行基本的文件操作。你可以根據(jù)需要調(diào)整這些示例以滿足你的需求。