index.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package openfile
  2. import (
  3. "io/ioutil"
  4. "log"
  5. "os"
  6. )
  7. type FileUtils struct {
  8. }
  9. // Exists 判断所给路径文件或文件夹是否存在
  10. func (FileUtils) Exists(path string) bool {
  11. _, err := os.Stat(path) //os.Stat获取文件信息
  12. if err != nil {
  13. if os.IsExist(err) {
  14. return true
  15. }
  16. return false
  17. }
  18. return true
  19. }
  20. // Create 创建文件
  21. func Create(path string) {
  22. f, err := os.Create(path)
  23. defer f.Close()
  24. if err != nil {
  25. log.Fatalf("db connect error: %#v\n", err.Error())
  26. }
  27. }
  28. // IsDir 判断所给路径是否为文件夹
  29. func (FileUtils) IsDir(path string) bool {
  30. s, err := os.Stat(path)
  31. if err != nil {
  32. return false
  33. }
  34. return s.IsDir()
  35. }
  36. // IsFile 判断所给路径是否为文件
  37. func (f FileUtils) IsFile(path string) bool {
  38. return !f.IsDir(path)
  39. }
  40. // RemoveFile 删除文件,参数文件路径
  41. func (f FileUtils) RemoveFile(path string) (bool, error) {
  42. //删除文件
  43. err := os.Remove(path)
  44. if err != nil {
  45. return false, err
  46. }
  47. return true, nil
  48. }
  49. // OpenFileRdonly 打开文件只读模式 文件不存会直接进项创建
  50. func (f FileUtils) OpenFileRdonly(path string) (*os.File, error) {
  51. return os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 0666)
  52. }
  53. // OpenFileWronly 打开文件只写模式,若文件不存在进行创建
  54. func (f FileUtils) OpenFileWronly(path string) (*os.File, error) {
  55. return os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
  56. }
  57. // OpenFileAppend 打开文件在文件后面追加数据,文件文件不存在会进行创建
  58. func (f FileUtils) OpenFileAppend(path string) (*os.File, error) {
  59. return os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
  60. }
  61. // FileCopy 进行文件复制操作
  62. func (f FileUtils) FileCopy(oldPath, newPath string) (bool, error) {
  63. data, err := ioutil.ReadFile(oldPath)
  64. if err != nil {
  65. return false, err
  66. }
  67. err = ioutil.WriteFile(newPath, data, 0666)
  68. if err != nil {
  69. return false, err
  70. }
  71. return true, nil
  72. }