kotlinでandroidでよく使われるツールクラスをいくつか書きました

8140 ワード

最近kotlin言語を勉強して、androidでよく使われるツールクラスFileUtilsを書きました.ktファイル操作クラスマルチレベルファイルディレクトリmkDir(dirpah:String)ファイルcreatFile(file Path:String)削除ファイルdelFile(filepath:File)削除削除フォルダdelDir(dirpath:String)SDカード上のファイルまたはディレクトリ名renameFile(oldFilePath:String,newFilePath:String)を変更するモバイルコピー読み取りファイルなどの機能githubアドレス個人ブログへようこそ
import android.os.Environment
import java.io.*

/**
 * Created by laijian on 2017/8/4.
 *        
 */
object FileUtils {

    /**
     *      
     */
    fun getRootDir(): String {

        return if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            Environment.getExternalStorageDirectory()
                    .absolutePath
        } else {
            ""
        }

    }

    /**
     *         
     * dirPath     
     */
    fun mkDir(dirPath: String) {

        val dirArray = dirPath.split("/".toRegex())
        var pathTemp = ""
        for (i in 1 until dirArray.size) {
            pathTemp = "$pathTemp/${dirArray[i]}"
            val newF = File("${dirArray[0]}$pathTemp")
            if (!newF.exists()) {
                val cheatDir: Boolean = newF.mkdir()
                println(cheatDir)
            }
        }

    }

    /**
     *     
     *
     * dirpath     
     * fileName     
     */
    fun creatFile(dirPath: String = getRootDir(), fileName: String) {
        val file = File("$dirPath/$fileName")
        if (!file.exists()) {
            file.createNewFile()
        }

    }

    /**
     *     
     * filePath     
     */
    fun creatFile(filePath: String) {
        val file = File(filePath)
        if (!file.exists()) {
            file.createNewFile()
        }
    }

    /**
     *     
     * filePath     
     */
    fun creatFile(filePath: File) {
        if (!filePath.exists()) {
            filePath.createNewFile()
        }
    }

    /**
     *     
     *
     * dirpath     
     * fileName     
     */
    fun delFile(dirpath: String = getRootDir(), fileName: String): Boolean {
        val file = File("$dirpath/$fileName")
        if (file.checkFile()) {
            return false
        }
        return file.delete()
    }

    /**
     *      
     *  filepath     
     */
    fun delFile(filepath: File): Boolean {
        if (filepath.checkFile()) {
            return false
        }
        return filepath.delete()
    }

    /**
     *      
     *  filepath     
     */
    fun delFile(filepath: String): Boolean {
        val file = File(filepath)
        if (file.checkFile()) {
            return false
        }
        return file.delete()
    }


    /**
     *      
     * dirPath     
     */
    fun delDir(dirpath: String) {
        val dir = File(dirpath)
        deleteDirWihtFile(dir)
    }

    fun deleteDirWihtFile(dir: File?) {
        if (dir!!.checkFile())
            return
        for (file in dir.listFiles()) {
            if (file.isFile)
                file.delete() //       
            else if (file.isDirectory)
                deleteDirWihtFile(file) //           
        }
        dir.delete()//       
    }

    private fun File.checkFile(): Boolean {
        return this == null || !this.exists() || !this.isDirectory
    }

    /**
     *   SD         
     * oldFilePath          
     * newFilePath          
     */
    fun renameFile(oldFilePath: String, newFilePath: String): Boolean {
        val oldFile = File(oldFilePath)
        val newFile = File(newFilePath)
        return oldFile.renameTo(newFile)
    }


    /**
     *       
     * srcFile   
     * destFile    
     */
    @Throws(IOException::class)
    fun copyFileTo(srcFile: File, destFile: File): Boolean {
        return if (srcFile.isDirectory || destFile.isDirectory) {
            false
        } else {
            val fis = FileInputStream(srcFile)
            val fos = FileOutputStream(destFile)
            fis.copyTo(fos)
            fos.flush()
            CloseIoUtils.closeIO(fos, fis)
            true
        }
    }

    /**
     *               
     * srcDir    
     * destDir     
     */
    fun copyFilesTo(srcDir: File, destDir: File): Boolean {
        if (!srcDir.isDirectory || !destDir.isDirectory) return false//        
        if (!destDir.exists()) return false//           
        val srcFiles = srcDir.listFiles()
        srcFiles.forEach {
            if (it.isFile) {
                val destFile = File("${destDir.path}/${it.name}")
                copyFileTo(it, destFile)
            } else {
                val theDestDir = File("${destDir.path}/${it.name}")
                copyFilesTo(it, theDestDir)
            }
        }

        return true
    }

    /**
     *       
     */
    fun moveFileTo(srcFile: File, destFile: File): Boolean {
        if (srcFile.isDirectory || destFile.isDirectory) return false
        val iscopy = copyFileTo(srcFile, destFile)
        return if (!iscopy) {
            false
        } else {
            delFile(srcFile)
            true
        }

    }

    /**
     *                
     * srcDir    
     * destDir     
     */
    @Throws(IOException::class)
    fun moveFilesTo(srcDir: File, destDir: File): Boolean {
        if (!srcDir.isDirectory or !destDir.isDirectory) {
            return false
        } else {
            val srcDirFiles = srcDir.listFiles()
            srcDirFiles.forEach {
                if (it.isFile) {
                    val oneDestFile = File("${destDir.path}/${it.name}")
                    moveFileTo(it, oneDestFile)
                    delFile(it)
                } else {
                    val oneDestFile = File(destDir.path + "//"
                            + it.name)
                    moveFilesTo(it, oneDestFile)
                    delDir(it.absolutePath)
                }

            }
            return true
        }

    }

    /**
     *    byte  
     * file     
     */
    @Throws(IOException::class)
    fun file2byte(file: File): ByteArray? {
        var bytes: ByteArray? = null
        if (file != null) {
            val inp = FileInputStream(file)
            val length = file.length() as Int
            if (length > Integer.MAX_VALUE) {//          int    
                inp.close()
                return null
            }
            bytes = inp.readBytes(length)
            CloseIoUtils.closeIO(inp)
        }
        return bytes
    }

    /**
     *     
     * filePath     
     */
    fun readFile(filePath: File): String? {
        if (!filePath.isFile) {
            return null
        } else {
            return filePath.readText()
        }
    }

    /**
     *     
     * strPath     
     */
    fun readFile(strPath: String): String? {
        return readFile(File(strPath))
    }

    /**
     * InputStream     
     */
    fun readInp(inp: InputStream): String? {
        val bytes: ByteArray = inp.readBytes()
        return String(bytes)
    }

    /**
     * BufferedReader     
     */
    fun readBuff(buff: BufferedReader): String? {
        return buff.readText()
    }

    /**
     *     
     */
    fun writeText(filePath: File, content: String) {
        creatFile(filePath)
        filePath.writeText(content)
    }

    /**
     *     
     */
    fun appendText(filePath: File, content: String) {
        creatFile(filePath)
        filePath.appendText(content)
    }

    /**
     *     
     */
    fun appendBytes(filePath: File, array: ByteArray) {
        creatFile(filePath)
        filePath.appendBytes(array)
    }

    /**
     *       
     */
    fun getLeng(filePath: File): Long {
        return if (!filePath.exists()) {
            -1
        } else {
            filePath.length()
        }
    }

    /**
     *      
     */
    fun sortByTime(filePath: File): Array? {
        if (!filePath.exists()) {
            return null
        }
        val files: Array = filePath.listFiles()
        if (files.isEmpty()) {
            return null
        }
        files.sortBy { it.lastModified() }
        files.reverse()
        return files

    }


}