How to move a directory and its contents to a different location in Kotlin
How to move a directory and its contents to a different location in Kotlin.
Here is a step-by-step tutorial on how to move a directory and its contents to a different location in Kotlin.
- Import the necessary packages:
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
- Define the source and destination directories:
val sourceDir = File("path/to/source/directory")
val destDir = File("path/to/destination/directory")
Replace "path/to/source/directory" and "path/to/destination/directory" with the actual paths of your source and destination directories.
- Check if the source directory exists:
if (sourceDir.exists() && sourceDir.isDirectory) {
// Directory exists, proceed with moving
} else {
// Source directory does not exist
println("Source directory does not exist.")
return
}
- Create the destination directory if it doesn't exist:
if (!destDir.exists()) {
destDir.mkdirs()
}
- Move the directory and its contents:
try {
Files.move(sourceDir.toPath(), destDir.toPath(), StandardCopyOption.REPLACE_EXISTING)
println("Directory moved successfully.")
} catch (e: Exception) {
println("Failed to move directory: ${e.message}")
}
- Run the program and check the console output for success or failure messages.
Here's a complete example of moving a directory and its contents:
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
fun main() {
val sourceDir = File("path/to/source/directory")
val destDir = File("path/to/destination/directory")
if (sourceDir.exists() && sourceDir.isDirectory) {
if (!destDir.exists()) {
destDir.mkdirs()
}
try {
Files.move(sourceDir.toPath(), destDir.toPath(), StandardCopyOption.REPLACE_EXISTING)
println("Directory moved successfully.")
} catch (e: Exception) {
println("Failed to move directory: ${e.message}")
}
} else {
println("Source directory does not exist.")
}
}
Remember to replace "path/to/source/directory" and "path/to/destination/directory" with the actual paths of your source and destination directories before running the code.