1.建立与打开
建立文件函数:
func Create(name string) (file *File, err Error)
func NewFile(fd int, name string) *File
打开文件函数:
func Open(name string) (file *File, err Error)
func OpenFile(name string, flag int, perm uint32) (file *File, err Error)
2.写文件
写文件函数:
func (file *File) Write(b []byte) (n int, err Error)
func (file *File) WriteAt(b []byte, off int64) (n int, err Error)
func (file *File) WriteString(s string) (ret int, err Error)
实例:
package main
import (
“os”
“fmt”
)
func main() {
userFile := “test.txt”
fout,err := os.Create(userFile)
defer fout.Close()
if err != nil {
fmt.Println(userFile,err)
return
}
for i:= 0;i<10;i++ {
fout.WriteString(“www.godeye.org!\r\n”)
fout.Write([]byte(“www.godeye.org!\r\n”))
}
}
3.读文件
读文件函数:
func (file *File) Read(b []byte) (n int, err Error)
func (file *File) ReadAt(b []byte, off int64) (n int, err Error)
实例:
package main
import (
“fmt”
“os”
)
func main() {
userFile := “test.txt”
fin, err := os.Open(userFile)
defer fin.Close()
if err != nil {
fmt.Println(userFile, err)
return
}
buf := make([]byte, 1024)
for {
n, _ := fin.Read(buf)
if 0 == n {
break
}
os.Stdout.Write(buf[:n])
}
}
4.删除文件
Go语言里面删除文件和删除文件夹是同一个函数
func Remove(name string) Error
实例:
package main
import (
“os”
)
func main() {
userFile := “godeye.txt”
os.Remove(userFile)
}
5.遍历文件夹
package main
import (
“flag”
“fmt”
“os”
“path/filepath”
)
func getFilelist(path string) {
err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if f.IsDir() {
return nil
}
fmt.Printf(path)
return nil
})
if err != nil {
fmt.Printf(“filepath.Walk() returned %v\n”, err)
}
}
func main() {
getFilelist(“src”)
}
6.经典的文件上传
这里给出2个文件,一个是服务端处理程序upload.go,一个是模板页面upload.html
先看upload.go
package main
import (
“fmt”
“html/template”
“io”
“log”
“net/http”
“os”
)
var buf []byte
func upload(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
if r.Method == “GET” {
t, err := template.ParseFiles(“upload.html”)
checkErr(err)
t.Execute(w, nil)
} else {
file, handle, err := r.FormFile(“file”)
checkErr(err)
f, err := os.OpenFile(“./test/”+handle.Filename, os.O_WRONLY|os.O_CREATE, 0666)
io.Copy(f, file)
checkErr(err)
defer f.Close()
defer file.Close()
fmt.Println(“upload success”)
}
}
func checkErr(err error) {
if err != nil {
err.Error()
}
}
func main() {
http.HandleFunc(“/upload”, upload)
err := http.ListenAndServe(“:8888”, nil)
if err != nil {
log.Fatal(“listenAndServe: “, err)
}
}