1 回答
TA贡献1815条经验 获得超10个赞
下面是我想出的代码: 接受有关如何使用 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
}
- 1 回答
- 0 关注
- 117 浏览
添加回答
举报