代码改变世界

go 通过bufio 写文件

2023-02-01 20:06  糯米粥  阅读(82)  评论(0编辑  收藏  举报
bufio是先写道缓冲区,通过 Flush() 更新
func writeFile(content, fileName string) {
    create, err := os.Create(fileName) // 如果文件已存在,会将文件清空。

    if err != nil {
        panic(err)
    }
    defer create.Close()
    writer := bufio.NewWriter(create)
    //writer.WriteString(content)
    fmt.Fprint(writer, content)
    writer.Flush()
}

 

 

func main() {
    writeFile("测试91", "./all/files/test2.txt")

}

 

func main1() {
    writeFile("测试9", "abc1.txt")

    http.HandleFunc("/list/", func(writer http.ResponseWriter, request *http.Request) {
        //request.URL.Path
        //writer.Write()

        //err := errors.New("dd")

        file, err := os.Open(request.URL.Path)
        if err != nil {
            http.Error(writer, err.Error(), http.StatusInternalServerError)
            //或者
            http.Error(writer, http.StatusText(http.StatusNotFound), http.StatusNotFound)
            //文件不存在
            os.IsNotExist(err)

            //没有权限
            os.IsPermission(err)

            return
        }
        defer file.Close()

        bytes, err := io.ReadAll(file)
        if err != nil {
            panic(err)
        }
        writer.Write(bytes)
    })

    http.ListenAndServe(":8888", nil)
}