How to move a file to a different directory in Kotlin
How to move a file to a different directory in Kotlin.
Here's a detailed step-by-step tutorial on how to move a file to a different directory in Kotlin.
- Import the necessary classes and functions:
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
- Specify the source file and the destination directory:
val sourceFile = File("path/to/source/file.txt")
val destinationDir = File("path/to/destination/directory")
Replace "path/to/source/file.txt" with the actual path to your source file and "path/to/destination/directory" with the actual path to your destination directory.
- Check if the source file exists:
if (sourceFile.exists()) {
// File exists, proceed with moving
} else {
// File does not exist, handle the error
}
- Create the destination directory if it doesn't exist:
if (!destinationDir.exists()) {
destinationDir.mkdirs()
}
- Move the file to the destination directory:
val destinationFile = File(destinationDir, sourceFile.name)
Files.move(sourceFile.toPath(), destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
This code creates a new File object for the destination file by combining the destination directory and the name of the source file. Then, it uses the Files.move() function to move the source file to the destination file, with the StandardCopyOption.REPLACE_EXISTING option to replace any existing file with the same name.
- Handle any exceptions that may occur during the file move:
try {
Files.move(sourceFile.toPath(), destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
println("File moved successfully.")
} catch (e: Exception) {
println("Failed to move the file: ${e.message}")
}
Enclose the file move code in a try-catch block to catch any exceptions that may occur, such as IOException or SecurityException. In case of an exception, the error message will be printed.
That's it! You have successfully moved a file to a different directory in Kotlin. You can customize this code according to your specific requirements and handle any additional scenarios as needed.