我正在尝试使用os.Replace()将文件从我的C盘移动到我的H盘.
代码如下:
func MoveFile(source string, destination string) {
err := os.Rename(source, destination)
if err != nil {
fmt.Println(err)
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行代码时,我收到以下错误:
rename C:\old\path\to\file.txt H:\new\path\to\file.txt: The system cannot move the file to a different disk drive.
Run Code Online (Sandbox Code Playgroud)
我在GitHub上发现了这个问题,指出了问题,但似乎他们不会更改此功能以允许它在不同的磁盘驱动器上移动文件.
我已经搜索了移动文件的其他可能性,但在标准文档或互联网中没有找到任何内容.
那么,我现在该怎么做才能在不同的磁盘驱动器上移动文件?
yal*_*lue 11
正如评论所说,您需要在另一个磁盘上创建一个新文件,复制内容,然后删除原始文件.它的简单使用os.Create,io.Copy以及os.Remove:
import (
"fmt"
"io"
"os"
)
func MoveFile(sourcePath, destPath string) error {
inputFile, err := os.Open(sourcePath)
if err != nil {
return fmt.Errorf("Couldn't open source file: %s", err)
}
outputFile, err := os.Create(destPath)
if err != nil {
inputFile.Close()
return fmt.Errorf("Couldn't open dest file: %s", err)
}
defer outputFile.Close()
_, err = io.Copy(outputFile, inputFile)
inputFile.Close()
if err != nil {
return fmt.Errorf("Writing to output file failed: %s", err)
}
// The copy was successful, so now delete the original file
err = os.Remove(sourcePath)
if err != nil {
return fmt.Errorf("Failed removing original file: %s", err)
}
return nil
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3121 次 |
| 最近记录: |