登录
首页 >  Golang >  Go问答

如何最小化golang文件夹重构以减少文件修改

来源:stackoverflow

时间:2024-03-15 23:09:28 359浏览 收藏

在 Go 中遇到一个问题,需要修改程序生成的多个文件,但无法重命名或移动它们。该程序持续输出文件,且每次都需要对每一份文件进行文本修改,然后才能供其他程序使用。为了减少文件修改次数,需要在文件创建后对其进行一次性修改,防止其他进程使用该文件。

问题内容

我遇到了一个程序正在输出文件的情况。为了修复该文件,我必须更改一行文本。我不拥有该程序的源代码,因此我必须更改该程序生成的每个文件,以便另一个程序可以正确使用它。

由于该过程的性质,我无法重命名文件或移动它们。

因此,我希望看到任何新文件放入(通过循环和睡眠就足够容易了)并更改文件,但只执行一次,因为其他进程需要出现并使用该文件。

我用 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  tag is in the file
            b := bytes.Contains(bs, []byte(""))

            //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(""), []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 
}

本篇关于《如何最小化golang文件夹重构以减少文件修改》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>