file - 如何创建golang热文件夹只修改一次文件

标签 file go

我有一个程序正在输出文件的情况。为了修复文件,我必须更改一行文本。我不拥有该程序的源代码,因此我必须更改该程序吐出的每个文件,以便其他程序可以正确使用它。
由于该过程的性质,我无法重命名文件或移动它们。
因此,我希望看到任何放入的新文件(通过循环和 sleep 很容易)并更改文件,但只执行一次,因为其他进程需要出现并使用此文件。
我在 Go 中编写了许多类似的应用程序,但总是被允许移动文件。

最佳答案

下面是我想出的代码: 接受有关如何使用 Seeker 执行此操作的建议,因为我只删除文件中的一行文本。

package main

import (
    "time"
    "fmt"       
    "io/ioutil"
    "os"
    "bytes"
    "strings"
)

const dir = "dir00003"

func main() {

fmt.Println("Running...")

//Go into a loop forever
for {

    //Wait 60 seconds before taking any action. 
    time.Sleep(60 * time.Second)
    //Read all of the file data for all files in the directory: 
    files, err := ioutil.ReadDir(dir)
    if err != nil {fmt.Println("Failed to read transfer folder. There must be a folder named `dir00003`!"); continue}

    for _, v := range files {

        //if this is an index file, skip over it as we don't care: 
        if strings.Contains(v.Name(), "pmi") {continue}

        //if the file was created within the last 2 minutes, we should check if we need to modify it
        if time.Now().Sub(v.ModTime()) < (time.Minute * 2) {

            //open the file 
            f, err := os.Open(fmt.Sprintf("%s/%s", dir, v.Name()))
            if err != nil {fmt.Printf("\tCouldn't open file: %s\n", v.Name()); continue}

            defer f.Close()
            //read all of the bytes of the file
            bs, err := ioutil.ReadAll(f)
            if err != nil {fmt.Printf("\tCouldn't read bytes from %s\n", v.Name()); continue}

            //see if the <program_parameters/> tag is in the file
            b := bytes.Contains(bs, []byte("<program_parameters/>"))

            //if the tag is in the file, we should replace it, otherwise we move on to the next file
            if b {
                //replace the tag with nothing. Only look for the first instance and then abort the process of replacing.
                rbs := bytes.Replace(bs, []byte("<program_parameters/>"), []byte(""), 1)
                //close the file so we can delete it. 
                f.Close()
                //delete the exisint file. 
                os.Remove(fmt.Sprintf("%s/%s", dir, v.Name()))

                //create a new file with the same original name:
                nf, err := os.Create(fmt.Sprintf("%s/%s", dir, v.Name()))
                if err != nil {fmt.Printf("\tFailed to create new file for %s\n", v.Name()); continue}

                //write all of the bytes that we have in memory to our new file. 
                _, err = nf.Write(rbs)
                if err != nil {fmt.Println("Failed to write to new file %s\n", v.Name()); continue}
                //close our new file
                nf.Close()

                fmt.Printf("Modified new file: %s", v.Name())

            } else {
                continue
            }

        }

    

    }

    fmt.Printf("\nDone with round\n")

}

fmt.Println("PROGRAM STOPPED RUNNING!!")

return 
}

关于file - 如何创建golang热文件夹只修改一次文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62805974/

相关文章:

go - 如何将 float 转换为复数?

sockets - 许多客户端连接到 Go 服务器时出错

r - 使用 Rserve 和 Roger 从 golang 执行 R 脚本

java - 在内部目录中找到一堆文件

file - "directory"或 "file"的意思是什么?

c++ - 使用 boost::mapped_region 生成文件以进一步写入?

Golang for select 循环消耗 100% 的 cpu

从函数和调用者到终端的 Golang 错误处理

java - 如何从Java中的桌面调用文件?

C:读取二进制文件输出零