write.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2025 BackendServerTemplate Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package fileutils
  5. import (
  6. "github.com/SongZihuan/BackendServerTemplate/tool/utils/cleanstringutils"
  7. "os"
  8. "strings"
  9. )
  10. func Write(filePath string, dat string) error {
  11. // 尝试打开文件
  12. file, err := os.OpenFile(filePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
  13. if err != nil {
  14. return err
  15. }
  16. defer func() {
  17. _ = file.Close()
  18. }()
  19. _, err = file.Write([]byte(dat))
  20. return err
  21. }
  22. func WriteBytes(filePath string, dat []byte) error {
  23. // 尝试打开文件
  24. file, err := os.OpenFile(filePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
  25. if err != nil {
  26. return err
  27. }
  28. defer func() {
  29. _ = file.Close()
  30. }()
  31. _, err = file.Write(dat)
  32. return err
  33. }
  34. func WriteEmpty(filePath string) error {
  35. // 尝试打开文件
  36. file, err := os.OpenFile(filePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
  37. if err != nil {
  38. return err
  39. }
  40. defer func() {
  41. _ = file.Close()
  42. }()
  43. return err
  44. }
  45. func AppendOnExistsFile(filePath string, dat string) error {
  46. // 尝试打开文件(若文件不存在则返回错误)
  47. file, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0644)
  48. if err != nil {
  49. return err
  50. }
  51. defer func() {
  52. _ = file.Close()
  53. }()
  54. _, err = file.Write([]byte(dat))
  55. return err
  56. }
  57. // CheckFileByLine 检查文件每一行,若fn返回 true 则本函数返回 true,否则返回false。
  58. // 传入 fn 的字符串不以 \n 结尾,空字符串也会传入
  59. func CheckFileByLine(filePath string, fn func(string) bool) (bool, error) {
  60. dat, err := os.ReadFile(filePath)
  61. if err != nil {
  62. return false, err
  63. }
  64. fileLine := strings.Split(cleanstringutils.GetString(string(dat)), "\n")
  65. for _, l := range fileLine {
  66. if fn(l) {
  67. return true, nil
  68. }
  69. }
  70. return false, nil
  71. }