如何在不覆盖 Go 中的现有文件的情况下复制文件?
How do I copy a file without overwriting an existing file in Go?
如果文件存在,如何使用给定名称创建新文件
例如:如果 word_destination.txt 存在,将内容复制到 word_destination(1).txt
如有任何帮助,我们将不胜感激...
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
src := ./word_source.txt
desti := ./folder/word_destination.txt
//if file exists want to copy it to the word_destination(1).txt
if _, err := os.Stat(desti); err == nil {
// path/to/whatever exists
fmt.Println("File Exists")
} else {
fmt.Println("File does not Exists")
bytesRead, err := ioutil.ReadFile(src)
if err != nil {
log.Fatal(err)
}
func tryCopy(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(dst, os.O_CREATE| os.O_EXCL, 0644)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
return err
}
return out.Close()
}
// ......
if _, err := os.Stat(desti); err == nil {
// path/to/whatever exists
fmt.Println("File Exists")
for i := 1; ; i++ {
ext := filepath.Ext(desti)
newpath := fmt.Sprintf("%s(%d)%s", strings.TrimSuffix(desti, ext), i, ext)
err := tryCopy(desti, newpath)
if err == nil {
break;
}
if os.IsExists(err) {
continue;
} else {
return err;
}
}
}
如果文件存在,如何使用给定名称创建新文件
例如:如果 word_destination.txt 存在,将内容复制到 word_destination(1).txt
如有任何帮助,我们将不胜感激...
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
src := ./word_source.txt
desti := ./folder/word_destination.txt
//if file exists want to copy it to the word_destination(1).txt
if _, err := os.Stat(desti); err == nil {
// path/to/whatever exists
fmt.Println("File Exists")
} else {
fmt.Println("File does not Exists")
bytesRead, err := ioutil.ReadFile(src)
if err != nil {
log.Fatal(err)
}
func tryCopy(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(dst, os.O_CREATE| os.O_EXCL, 0644)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
return err
}
return out.Close()
}
// ......
if _, err := os.Stat(desti); err == nil {
// path/to/whatever exists
fmt.Println("File Exists")
for i := 1; ; i++ {
ext := filepath.Ext(desti)
newpath := fmt.Sprintf("%s(%d)%s", strings.TrimSuffix(desti, ext), i, ext)
err := tryCopy(desti, newpath)
if err == nil {
break;
}
if os.IsExists(err) {
continue;
} else {
return err;
}
}
}