zoukankan      html  css  js  c++  java
  • kotlin单个文件及文件夹复制例子

    最近学习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("完成")
    }
  • 相关阅读:
    HDU 2236 无题Ⅱ
    Golden Tiger Claw(二分图)
    HDU 5969 最大的位或 (思维,贪心)
    HDU 3686 Traffic Real Time Query System (图论)
    SCOI 2016 萌萌哒
    Spring Boot支持控制台Banner定制
    构建第一个Spring Boot程序
    Spring Boot重要模块
    Java fastjson JSON和String互相转换
    BCompare 4 Windows激活方法【试用期30天重置】
  • 原文地址:https://www.cnblogs.com/it-tsz/p/11646392.html
Copyright © 2011-2022 走看看