华为仓颉-写文件操作

236 阅读1分钟

仓颉编程语言提供了 fs 包来支持通用文件系统任务。虽然不同的操作系统对于文件系统提供的接口有所不同,但是仓颉编程语言抽象出以下一些共通的功能,通过统一的功能接口,屏蔽不同操作系统之间的差异,来简化我们的使用。 这些常规操作任务包括:创建文件/目录、读写文件、重命名或移动文件/目录、删除文件/目录、复制文件/目录、获取文件/目录元数据、检查文件/目录是否存在。具体 API 可以查阅库文档。 使用文件系统相关的功能需要导入 fs 包

其实文件流都差不多,仓颉主要是简单


package cangjieDemo
import std.fs.*
struct fileOption{

    func fileExists(): Bool{
        let exists = File.exists("/Users/x/workspaces/cangjie/first/first.cj")
        return exists
    }

    func create():Bool{
         let file = File.create("/Users/x/workspaces/cangjie/tempFile.txt")
        file.write("hello, world!".toArray())
        return true
    }
    func read(){
        let file2 = File.openRead("/Users/x/workspaces/cangjie/tempFile.txt")
        let bytes = file2.readToEnd() // 读取所有数据
        println(bytes)
    }
}


package cangjieDemo

import cangjieDemo.demo1.testTuple

main(): Int64 {
   var fileOption = fileOption()
   var e = fileOption.fileExists()
   println(e)

   fileOption.read()
    return 0
}



输出结果

image.png