01-Golang Files and I/O
文章目录
Golang Files and I/O
Table of Contents
- Table of Contents
- 一:读文件
- 二:写文件
- 三:File Operations
- 四:目录相关操作 Directory Operations
- 五:File Path Operations
- 六:IO related interface
一:读文件
1.1 读一个 whole 文件
|
|
1.2 读一个文件,close
|
|
1.3 read file by line
|
|
二:写文件
2.1 Write the whole file
|
|
2.2 Open file for writing
|
|
2.3 Open file for appending
|
|
2.4 Write to a file
|
|
2.5 File permissions when creating files
使用 os.Create 或创建新文件时 os.OpenFile,需要为新文件提供文件权限。
对于大多数情况 0644 是一个不错的选择。
这些是八进制格式的 Unix 样式权限。
三:File Operations
3.1 获取文件 size
|
|
3.2 获取文件 information
|
|
3.3 检查文件是否 Exist
|
|
3.4 Delete File
|
|
3.5 Rename File
|
|
3.6 Copy a File
|
|
四:目录相关操作 Directory Operations
4.1 Create directory
|
|
os.Mkdir
only succeeds if parent directory of dir already exists.os.MkdirAll
will create all intermediary directories.0755
describes permissions for the directory.
4.2 Remove Directory
os.Remove
only works for empty directories i.e. directories without any files of sub-directories.1 2 3 4 5
dir := "my_dir" err := os.Remove(dir) if err != nil { fmt.Printf("os.Remove('%s') failed with '%s'\n", path, err) }
os.RemoveAll
removes the directory and all its children (files and sub-directories).1 2 3 4 5
dir := "my_dir" err := os.RemoveAll(dir) if err != nil { fmt.Printf("os.RemoveAll('%s') failed with '%s'\n", path, err) }
4.3 列出目录下面的文件 List files in a directory
|
|
4.4 Recursive 递归的 List 文件
|
|
五:File Path Operations
5.1 Join a path
|
|
5.2 Split a path into a directory and file
|
|
5.3 Split list of paths
|
|
5.4 Get file name from path
|
|
5.5 Get directory name from path
|
|
5.6 获取文件拓展名 Get file extension
|
|
六:IO related interface
6.1 io.Reader
io.Reader
是读取顺序字节流的关键的抽象;Read
函数将最多 len(p) byte 读入一个 buffer 缓冲区 p,返回一个读取的字节和错误的状态;- 当它到达文件结尾的时候,返回一个
io.EOF
错误 io.Reader
不允许返回流中。为此,类型必须实现io.Seeker
或io.ReaderAt
接口;
|
|
6.2 io.Writer
io.Writer
用于写入顺序的字节流 bytes stream;Write
writes bytes inp
and returns the number of bytes written and error status.- Write 保证它会写入所有数据或返回错误,即如果返回的 n 是 < len(p) 则 err 必须非零;
1 2 3
type Writer interface{ Write (p []byte) (n int,err error) }
6.3 io.Closer
- Closer describes streams that must be explicitly closed.(Closer 描述必须显式的 close 的流);
- Close returns an error because it’s required in some real-world cases. For example, 在对文件进行缓冲写入时,Close 可能需要将剩余的缓冲数据刷新到文件中,这可能会失败.
|
|
6.4 io.ReaderAt
- io.ReaderAt is like io.Reader but allows to read at any position in the stream.
|
|
6.5 io.WriterAt
- io.WriterAt is like io.Write but allows to write at an arbitrary position in the stream.
1 2 3
type WriterAt interface { WriteAt(p []byte, off int64) (n int, err error) }
6.6 io.Seeker
- io.Seeker allows seeking within the stream. If you can seek, you can also implement io.ReaderAt and io.WriterAt.
|
|
文章作者 lucas
上次更新 2022-03-04 (b3cbdf7)