最近學習kotlin,把java中的單個文件及包含文件夾的文件
復制操作改寫為kotlin的代碼,主要熟悉kotlin文件操作以及遞歸調用操作方法
演示代碼如下:
package com.exam.filedemo
import java.io.*
import java.lang.Exception
import java.util.*
/**
* 單個文件復制
*/
fun copyfile(srcFile: File, destFile: File) {
var fis = FileInputStream(srcFile);
var fos = FileOutputStream(destFile)
var bis = BufferedInputStream(fis)
var bos = BufferedOutputStream(fos)
var buf = ByteArray(1024)
var len = 0;
while (true) {
len = bis.read(buf)
if (len == -1) break;
bos.write(buf, 0, len)
}
fis.close()
fos.close()
}
/**
* 帶文件夾復制
*/
fun copyDirToDir(srcFile: File, destFile: File) {
for (f in srcFile.listFiles()) {
//是文件就拷貝
var newfile = File(destFile.absolutePath, f.name)
if (f.isFile) {
println("${f.absolutePath}-->${newfile.absolutePath}")
copyfile(f, newfile)
} else { //如果是目錄就遞歸復制
//如果目標文件不存在,則創建
if (!newfile.exists()) {
if (!newfile.mkdir()) return
}
copyDirToDir(f, newfile)
}
}
return
}
/**
* 提示輸入文件目錄
*/
fun getDir(msg: String): String {
var path = ""
while (true) {
var sc = Scanner(System.`in`)
println("$msg")
path = sc.nextLine()
if (File(path).isDirectory) {
break;
}
}
return path
}
fun main() {
var srcFile = File("")
var destFile = File("")
srcFile = File(getDir("請輸入復制的源文件目錄:"))
destFile = File(getDir("請輸入復制的目標文件目錄:"))
try {
copyDirToDir(srcFile, destFile)
} catch (e: Exception) {
e.printStackTrace()
}
println("完成")
}