文件写入支持覆盖写入与追加写入支持
This commit is contained in:
parent
df8da44d0d
commit
c5908177a2
1
.gitignore
vendored
1
.gitignore
vendored
@ -19,4 +19,5 @@
|
||||
.idea
|
||||
.vscode
|
||||
*_test.go
|
||||
*.txt
|
||||
|
||||
|
40
file.go
40
file.go
@ -44,12 +44,13 @@ func File(workDir string, filePath string) *fileOperate {
|
||||
//
|
||||
// Date : 12:24 2022/5/22
|
||||
type fileOperate struct {
|
||||
workDir string
|
||||
filePath string
|
||||
autoCreate bool
|
||||
permission os.FileMode
|
||||
openFlag int
|
||||
fileHandler *os.File
|
||||
workDir string
|
||||
filePath string
|
||||
autoCreate bool
|
||||
permission os.FileMode
|
||||
openFlag int
|
||||
fileHandler *os.File
|
||||
clearHasContent bool // 文件写入时, 清空现有内容(覆盖写入), 默认追加写入
|
||||
}
|
||||
|
||||
// IsExist 文件是否存在
|
||||
@ -75,6 +76,7 @@ func (f *fileOperate) IsExist() (bool, bool, error) {
|
||||
// Date : 12:28 2022/5/22
|
||||
func (f *fileOperate) AutoCreate() *fileOperate {
|
||||
f.autoCreate = true
|
||||
f.openFlag = f.openFlag | os.O_CREATE
|
||||
return f
|
||||
}
|
||||
|
||||
@ -95,11 +97,26 @@ func (f *fileOperate) Permission(fileModel os.FileMode) *fileOperate {
|
||||
// Date : 13:40 2022/5/22
|
||||
func (f *fileOperate) SetOpenFlag(flagList ...int) *fileOperate {
|
||||
for _, flag := range flagList {
|
||||
if flag == os.O_CREATE {
|
||||
f.AutoCreate()
|
||||
continue
|
||||
}
|
||||
f.openFlag = f.openFlag | flag
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// SetClearHasContentForWrite 设置覆盖写入文件内容
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 16:41 2022/5/22
|
||||
func (f *fileOperate) SetClearHasContentForWrite() *fileOperate {
|
||||
f.clearHasContent = true
|
||||
f.openFlag = f.openFlag | os.O_TRUNC
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create 创建文件
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
@ -210,6 +227,17 @@ func (f *fileOperate) Write(content []byte) error {
|
||||
return errors.New("文件打开失败 : " + err.Error())
|
||||
}
|
||||
}
|
||||
if f.clearHasContent {
|
||||
// 覆盖写入
|
||||
if err := os.Truncate(f.filePath, 0); nil != err {
|
||||
return err
|
||||
}
|
||||
n, _ := f.fileHandler.Seek(0, io.SeekEnd)
|
||||
|
||||
_, writeErr := f.fileHandler.WriteAt(content, n)
|
||||
return writeErr
|
||||
}
|
||||
// 追加写入
|
||||
_, writeErr := f.fileHandler.Write(content)
|
||||
return writeErr
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user