чтение файла
This commit is contained in:
parent
186892989f
commit
46671879fc
@ -55,7 +55,7 @@ Epoch
|
||||
Парсинг URL (URL Parsing)
|
||||
Хеш SHA1 (SHA1 Hashes)
|
||||
Кодирование Base64 (Base64 Encoding)
|
||||
Reading Files
|
||||
Чтение файлов (Reading Files)
|
||||
Writing Files
|
||||
Line Filters
|
||||
File Paths
|
||||
|
@ -1,6 +1,6 @@
|
||||
// Reading and writing files are basic tasks needed for
|
||||
// many Go programs. First we'll look at some examples of
|
||||
// reading files.
|
||||
// Чтение и запись файлов это базовая задача, необходимая
|
||||
// для решения множества задач. Для начала мы рассмотрим
|
||||
// несколько примеров чтения файлов.
|
||||
|
||||
package main
|
||||
|
||||
@ -12,8 +12,9 @@ import (
|
||||
"os"
|
||||
)
|
||||
|
||||
// Reading files requires checking most calls for errors.
|
||||
// This helper will streamline our error checks below.
|
||||
// Чтение файлов требует проверок множества вызовов на
|
||||
// наличие ошибок. Эта функция-хелпер поможет нам
|
||||
// обрабатывать ошибки в одном месте.
|
||||
func check(e error) {
|
||||
if e != nil {
|
||||
panic(e)
|
||||
@ -22,28 +23,29 @@ func check(e error) {
|
||||
|
||||
func main() {
|
||||
|
||||
// Perhaps the most basic file reading task is
|
||||
// slurping a file's entire contents into memory.
|
||||
// Возможно, самая основная задача чтения файлов -
|
||||
// это сохранение всего содержимого файла в памяти.
|
||||
dat, err := ioutil.ReadFile("/tmp/dat")
|
||||
check(err)
|
||||
fmt.Print(string(dat))
|
||||
|
||||
// You'll often want more control over how and what
|
||||
// parts of a file are read. For these tasks, start
|
||||
// by `Open`ing a file to obtain an `os.File` value.
|
||||
// Вам часто может потребоваться больший контроль
|
||||
// над тем, как и какие части файла читаются. Для
|
||||
// решения этих задач начните с открытия файла,
|
||||
// чтобы получить значение `os.File`..
|
||||
f, err := os.Open("/tmp/dat")
|
||||
check(err)
|
||||
|
||||
// Read some bytes from the beginning of the file.
|
||||
// Allow up to 5 to be read but also note how many
|
||||
// actually were read.
|
||||
// Прочитаем несколько байт с начала файла. Будет
|
||||
// прочитано первые 5 байт, но также выведем,
|
||||
// сколько фактически было прочитано.
|
||||
b1 := make([]byte, 5)
|
||||
n1, err := f.Read(b1)
|
||||
check(err)
|
||||
fmt.Printf("%d bytes: %s\n", n1, string(b1[:n1]))
|
||||
|
||||
// You can also `Seek` to a known location in the file
|
||||
// and `Read` from there.
|
||||
// Вы так же можете получить конкретное место файла
|
||||
// с помощью `Seek` и выполнить `Read` оттуда.
|
||||
o2, err := f.Seek(6, 0)
|
||||
check(err)
|
||||
b2 := make([]byte, 2)
|
||||
@ -52,10 +54,10 @@ func main() {
|
||||
fmt.Printf("%d bytes @ %d: ", n2, o2)
|
||||
fmt.Printf("%v\n", string(b2[:n2]))
|
||||
|
||||
// The `io` package provides some functions that may
|
||||
// be helpful for file reading. For example, reads
|
||||
// like the ones above can be more robustly
|
||||
// implemented with `ReadAtLeast`.
|
||||
// Пакет `io` предоставляет некоторые функции, которые
|
||||
// могут быть полезны для чтения файлов. Например,
|
||||
// чтение, подобное приведенному выше, может быть
|
||||
// более надежно реализовано с помощью `ReadAtLeast`.
|
||||
o3, err := f.Seek(6, 0)
|
||||
check(err)
|
||||
b3 := make([]byte, 2)
|
||||
@ -63,22 +65,22 @@ func main() {
|
||||
check(err)
|
||||
fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))
|
||||
|
||||
// There is no built-in rewind, but `Seek(0, 0)`
|
||||
// accomplishes this.
|
||||
// Тут нет встроенной перемотки назад, но можно
|
||||
// использовать `Seek(0, 0)` для этого.
|
||||
_, err = f.Seek(0, 0)
|
||||
check(err)
|
||||
|
||||
// The `bufio` package implements a buffered
|
||||
// reader that may be useful both for its efficiency
|
||||
// with many small reads and because of the additional
|
||||
// reading methods it provides.
|
||||
// В пакете `bufio` реализован буферизованный ридер,
|
||||
// который может быть полезен из-за своей эффективности
|
||||
// при большом количестве небольших операций чтения, и
|
||||
// из-за наличия дополнительных методов чтения, которые
|
||||
// он предоставляет.
|
||||
r4 := bufio.NewReader(f)
|
||||
b4, err := r4.Peek(5)
|
||||
check(err)
|
||||
fmt.Printf("5 bytes: %s\n", string(b4))
|
||||
|
||||
// Close the file when you're done (usually this would
|
||||
// be scheduled immediately after `Open`ing with
|
||||
// `defer`).
|
||||
// Закройте файл, когда вы закончите использовать его
|
||||
// (обычно закрытие с `defer`'ом делается сразу после открытия).
|
||||
f.Close()
|
||||
}
|
||||
|
@ -8,4 +8,4 @@ go
|
||||
2 bytes @ 6: go
|
||||
5 bytes: hello
|
||||
|
||||
# Next we'll look at writing files.
|
||||
# Далее рассмотрим запись в файл.
|
||||
|
Loading…
x
Reference in New Issue
Block a user