Kotlin学习笔记四:文件操作

目录

前言

一、创建指令中心CommondLineTool

二、创建逻辑中心LogicCenter

三、 创建所需要的变量

 四、文件处理中心FileManager

 五、定义一个接口,提供模板

 最后调用测试即可


前言

主要介绍用接口来实现文件操作命令,后续会推出全新版本。

项目示例:

 

一、创建指令中心CommondLineTool

package kFile

import java.util.Scanner

/**
 * 第一步,创建指令中心
 */
class CommondLineTool {
    companion object {
        /**
         * by lazy 懒加载
         * 定义时不加载,使用时才加载
         * 只会被加载一次
         */
        val instance: CommondLineTool by lazy {
            CommondLineTool()
        }
    }
    fun start(){
        show()
        while (true){
            readCommond()
        }
    }
    private fun show(){
        println("欢迎使用爱疯18操作系统,请输入您的指令")
    }
    //输入指令
    private fun readCommond(){
        //先显示当前路径
        print("[$CURRENTNAME]# ")
        //判断有没有空格,如果有且只有一个,就用cmd1存储空格前的字符串
        // cmd2存储空格后面的字符串,其他不符合条件的就提示用户重新输入
        val scanner = Scanner(System.`in`)
        //trim()用于去除字符串两端的空白字符(空格、制表符、换行符等)
        val cmd = scanner.nextLine().trim()
        //是将 cmd 中的字符串按照空格进行分割,并返回一个字符串数组。
        val parts = cmd.split(" ")
        LogicCenter.instance.judge(parts.size,cmd,parts)
    }
}

二、创建逻辑中心LogicCenter

package kFile

import kotlin.system.exitProcess

/**
 *  逻辑中心
 */

class LogicCenter {
    companion object {
        /**
         * by lazy 懒加载
         * 定义时不加载,使用时才加载
         * 只会被加载一次
         */
        val instance: LogicCenter by lazy {
            LogicCenter()
        }
    }

    fun judge(judges : Int,cmd : String,parts : List<String>){
        when (judges){
            1 -> {
                when (cmd) {
                    "ls" -> FileManager().listFile(CURRENTPATH)
                    "exit" -> exitProcess(-1)
                    "pwd" -> FileManager().showCurrentPath(CURRENTPATH)
                    else -> println("输入的指令不对,请重新输入!")
                }
            }
            2 -> {
                val cmd1 = parts[0]
                val cmd2 = parts[1]
                if (cmd1 == "ls" && cmd2 == "-l") FileManager().listFileAndMemory(CURRENTPATH)
                else if (cmd1 == "mkdirs") FileManager().creatDirectory(CURRENTPATH,cmd2)
                else if (cmd1 == "mkdir") FileManager().creatFile(CURRENTPATH,cmd2)
                else if (cmd1 == "vim") FileManager().creatVim(CURRENTPATH,cmd2)
                else if (cmd1 == "cd" && cmd2 == ".." ) FileManager().cdBackFile(CURRENTPATH)
                else if (cmd1 == "cd") FileManager().cdFile(CURRENTPATH, cmd2)
                else if (cmd1 == "cat") FileManager().checkFile(CURRENTPATH,cmd2)
                else if (cmd1 == "rm") FileManager().delete(CURRENTPATH,cmd2)
                else println("输入的指令不对,请重新输入!")
            }
            3 -> {
                val cmd1 = parts[0]
                val cmd2 = parts[1]
                val cmd3 = parts[2]
                if (cmd1 == "mv") FileManager().move(CURRENTPATH,cmd2, cmd3)
                else if (cmd1 == "rn") FileManager().rename(CURRENTPATH,cmd2, cmd3)
                else if (cmd1 == "cp") FileManager().copy(CURRENTPATH,cmd2, cmd3)
                else println("输入的指令不对,请重新输入!")
            }
            else -> println("输入的指令不对,请重新输入!")
        }
    }
}

三、 创建所需要的变量

package kFile

import java.util.ArrayList

//这里记得改为自己的桌面
var CURRENTPATH :String = "C:/Users/汐风的游戏/OneDrive/桌面"

var CURRENTNAME = "desktop"

val PATHS :ArrayList<String> = arrayListOf()

 四、文件处理中心FileManager

package kFile

import java.io.File
import java.io.IOException
import java.lang.String.format

class FileManager :ICommondListener{
    override fun listFile(path: String) {
        val file = File(path)
        file.list()?.forEach {
            println(it)
        }
    }

    override fun listFileAndMemory(path: String) {
        val dir = File(path)
        dir.listFiles()?.forEach { file ->
            val fileSizeInBytes = file.length()
            val fileSizeInMB = fileSizeInBytes.toDouble() / (1024 * 1024)
            // 使用字符串格式化 "%.3f" 来保留小数点后三位
            println("${file.name}     ${format("%.3f",fileSizeInMB)} MB")
        }
    }

    //后面在来完善
    override fun showCurrentPath(path: String) {
        println(path)
    }

    override fun creatDirectory(path: String,name:String) {
        val dir = File(path,name)
        if(dir.mkdirs()){
            println("创建成功")
        }else println("创建失败")
    }

    override fun creatFile(path: String, name: String) {
        val dir = File("$path/$name")
        if(dir.mkdir()){
            println("创建成功")
        }else println("创建失败")
    }

    override fun creatVim(path: String, name: String) {
        val dir = File(path,name)
        if(dir.createNewFile()){
            println("创建成功")
        }else println("创建失败")
    }

    override fun cdFile(path: String, name: String) {
        PATHS.add(name)
        CURRENTPATH = "$path/$name"
        CURRENTNAME = "$CURRENTNAME/$name"
    }

    override fun cdBackFile(path: String) {
        //判断是否为空
        if(PATHS.isNotEmpty()){
            val len = PATHS[PATHS.size-1].length + 1
            val currentPath = removeLastNChars(CURRENTPATH, len)
            val currentName = removeLastNChars(CURRENTNAME, len)
            CURRENTPATH = currentPath
            CURRENTNAME = currentName
            PATHS.remove(PATHS[PATHS.size-1])
        }
    }

    override fun checkFile(path: String, name: String) {
        val dir = File(path,name)
        // 检查文件是否存在
        if (dir.exists()) {
            // 读取文件内容并打印到控制台
            val text = dir.readText()
            println(text)
        }else println("该文件不存在")
    }

    override fun delete(path: String, name: String) {
        val file = File(path,name)
        if(file.exists()) {
            if(deleteDirectory(file)) println("删除成功")
            else println("删除失败")
        }
        else println("该文件不存在")
    }
    //使用递归的方法来删除
    private fun deleteDirectory(directory: File): Boolean {
        if (directory.exists()) {
            directory.listFiles()?.forEach { file ->
                if (file.isDirectory) {
                    deleteDirectory(file)
                } else {
                    file.delete()
                }
            }
        }
        return directory.delete()
    }

    override fun move(path: String, src: String, dir: String) {
        //源文件地址
        val source = File(path,src)
        //目标文件地址
        val dsetnationDir = File(path,dir)
        //移动后地址
        val dest = File(dsetnationDir,src)
        // 检查要重命名的文件是否存在
        try {
            // 调用 renameTo() 方法进行重命名或移动
            if (source.renameTo(dest)) println("移动成功")
                else println("移动失败")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun rename(path: String, src: String, dir: String) {
        //源文件地址
        val source = File(path,src)
        //目标文件
        val dest = File(path,dir)
        try {
            // 调用 renameTo() 方法进行重命名或移动
            if (source.renameTo(dest)) println("重命名成功")
            else println("重命名失败")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun copy(path: String, src: String, dir: String) {
        val source = File(path, src)
        val destinationDir = File(path, dir)
        val result = File(destinationDir, src)
        try {
            // 复制文件
            copyRecursively(source, result)
            println("复制成功")
        } catch (e: IOException) {
            e.printStackTrace()
            println("复制失败: ${e.message}")
        }
    }
    private fun copyRecursively(source: File, destination: File) {
        if (source.isDirectory) {
            // Ensure the destination directory exists
            if (!destination.exists()) {
                destination.mkdirs()
            }

            // Copy each file/subdirectory from the source to the destination
            source.listFiles()?.forEach { file ->
                val destFile = File(destination, file.name)
                copyRecursively(file, destFile)
            }
        } else {
            // Copy the file
            source.copyTo(destination, overwrite = true)
        }
    }

    private fun removeLastNChars(input: String, n: Int): String {
        if (n >= input.length) {
            return ""
        }
        return input.substring(0, input.length - n)
    }
}

 五、定义一个接口,提供模板

package kFile

interface ICommondListener {
    fun listFile(path:String)
    fun listFileAndMemory(path:String)
    fun showCurrentPath(path: String)
    fun creatDirectory(path: String,name:String)
    fun creatFile(path: String,name:String)
    fun creatVim(path: String,name:String)
    fun cdFile(path: String,name:String)
    fun cdBackFile(path: String)
    fun checkFile(path: String,name: String)
    fun delete(path: String,name: String)
    fun move(path: String,src: String,dir: String)
    fun rename(path: String,src: String,dir: String)
    fun copy(path: String,src: String,dir: String)
}

 最后调用测试即可

package kFile

fun main() {
    CommondLineTool.instance.start()
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值