java/kotlin 讀取文件、寫入文件


package dh.btb.backend.utils
import java.io.*object FileUtil {

    /**
     * 創建文件
     * @param filePath 文件路徑(不要以/結尾)
     * @param fileName 文件名稱(包含后綴,如:ReadMe.txt)
     * @throws IOException
     */
    @Throws(IOException::class)
    fun createTxtFile(filePath: String, fileName: String): Boolean {
        var flag = false
        val filename = File("$filePath/$fileName")
        if (!filename.exists()) {
            filename.createNewFile()
            flag = true
        }
        return flag
    }

    /**
     * 寫文件
     *
     * @param content 文件內容
     * @param filePath 文件路徑(不要以/結尾)
     * @param fileName 文件名稱(包含后綴,如:ReadMe.txt)
     * 新內容
     * @throws IOException
     */
    fun writeTxtFile(content: String, filePath: String, fileName: String, append: Boolean): Boolean {
        var flag: Boolean = true
        val thisFile = File("$filePath/$fileName")
        try {
            if (!thisFile.parentFile.exists()) {
                thisFile.parentFile.mkdirs()
            }
            val fw = FileWriter("$filePath/$fileName", append)
            fw.write(content)
            fw.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return flag
    }

    /**
     * 讀TXT文件內容
     * @param filePath 文件路徑(不要以 / 結尾)
     * @param fileName 文件名稱(包含后綴,如:ReadMe.txt)
     * @return
     */
    @Throws(Exception::class)
    fun readTxtFile(filePath: String, fileName: String): String? {
        var result: String? = ""
        val fileName = File("$filePath/$fileName")
        var fileReader: FileReader? = null
        var bufferedReader: BufferedReader? = null
        try {
            fileReader = FileReader(fileName)
            bufferedReader = BufferedReader(fileReader)
            try {
                var read: String? = null
                while ({ read = bufferedReader.readLine();read }() != null) {
                    result = result + read + "\r\n"
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close()
            }
            if (fileReader != null) {
                fileReader.close()
            }
        }
        println("讀取出來的文件內容是:\r\n$result")
        return result
    }
}

fun main(args: Array<String>) {
    val service = FileUtil
    val pathName = "E:/temp"
    val fileName = "ReadMe.json"
    val content = "我現在在上班" +
            "比較忙的時候別來打擾我"
    service.createTxtFile(pathName, fileName)
    service.writeTxtFile(content, pathName, fileName, false)
    val str = service.readTxtFile(pathName, fileName)
    println(str)
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM