将文本文件读入字符串数组(并写入) [英] Read text file into string array (and write)

查看:109
本文介绍了将文本文件读入字符串数组(并写入)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

读取(和写入)文本文件进出字符串数组的能力是我相信的一个相当普遍的要求。从最初访问数据库的语言开始,它也非常有用。在Golang中是否存在?

例如 func ReadLines(sFileName string,iMinLines int)([] string,bool){

func WriteLines(saBuff []字符串,sFilename字符串)(bool){

我倾向于使用现有的而不是重复。

The ability to read (and write) a text file into and out of a string array is I believe a fairly common requirement. It is also quite useful when starting with a language removing the need initially to access a database. Does one exist in Golang?
e.g. func ReadLines(sFileName string, iMinLines int) ([]string, bool) {
and func WriteLines(saBuff[]string, sFilename string) (bool) {.
I would prefer to use an existing one rather than duplicate.

推荐答案

从Go1.1发布开始,有一个 bufio.Scanner API可以很容易地读取文件中的行。请看下面的例子,用Scanner重写:

As of Go1.1 release, there is a bufio.Scanner API that can easily read lines from a file. Consider the following example from above, rewritten with Scanner:

package main

import (
  "bufio"
  "fmt"
  "log"
  "os"
)

// readLines reads a whole file into memory
// and returns a slice of its lines.
func readLines(path string) ([]string, error) {
  file, err := os.Open(path)
  if err != nil {
    return nil, err
  }
  defer file.Close()

  var lines []string
  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    lines = append(lines, scanner.Text())
  }
  return lines, scanner.Err()
}

// writeLines writes the lines to the given file.
func writeLines(lines []string, path string) error {
  file, err := os.Create(path)
  if err != nil {
    return err
  }
  defer file.Close()

  w := bufio.NewWriter(file)
  for _, line := range lines {
    fmt.Fprintln(w, line)
  }
  return w.Flush()
}

func main() {
  lines, err := readLines("foo.in.txt")
  if err != nil {
    log.Fatalf("readLines: %s", err)
  }
  for i, line := range lines {
    fmt.Println(i, line)
  }

  if err := writeLines(lines, "foo.out.txt"); err != nil {
    log.Fatalf("writeLines: %s", err)
  }
}

这篇关于将文本文件读入字符串数组(并写入)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆