dougongnan2167 2015-03-28 02:54
浏览 108
已采纳

如何在Golang中读取大型平面文件

I have a flat file that has 339276 line of text in it for a size of 62.1 MB. I am attempting to read in all the lines, parse them based on some conditions I have and then insert them into a database.

I originally attempted to use a bufio.Scan() loop and bufio.Text() to get the line but I was running out of buffer space. I switched to using bufio.ReadLine/ReadString/ReadByte (I tried each) and had the same problem with each. I didn't have enough buffer space.

I tried using read and setting the buffer size but as the document says it actually a const that can be made smaller but never bigger that 64*1024 bytes. I then tried to use File.ReadAt where I set the starting postilion and moved it along as I brought in each section to no avail. I have looked at the following examples and explanations (not an exhaustive list):

Read text file into string array (and write) How to Read last lines from a big file with Go every 10 secs reading file line by line in go

How do I read in an entire file (either line by line or the whole thing at once) into a slice so I can then go do things to the lines?

Here is some code that I have tried:

                 file, err := os.Open(feedFolder + value)
                 handleError(err)
                 defer file.Close()
                 //              fileInfo, _ := file.Stat()
                 var linesInFile []string

             r := bufio.NewReader(file)
             for {
                     path, err := r.ReadLine("
") // 0x0A separator = newline

                     linesInFile = append(linesInFile, path)
                     if err == io.EOF {
                             fmt.Printf("End Of File: %s", err)
                             break
                     } else if err != nil {
                             handleError(err) // if you return error
                     }
             }
             fmt.Println("Last Line: ", linesInFile[len(linesInFile)-1])

Here is something else I tried:

var fileSize int64 = fileInfo.Size()
    fmt.Printf("File Size: %d\t", fileSize)
    var bufferSize int64 = 1024 * 60
    bytes := make([]byte, bufferSize)
    var fullFile []byte
    var start int64 = 0
    var interationCounter int64 = 1
    var currentErr error = nil
         for currentErr != io.EOF {
            _, currentErr = file.ReadAt(bytes, st)
            fullFile = append(fullFile, bytes...)
            start = (bufferSize * interationCounter) + 1
            interationCounter++
          }
     fmt.Printf("Err: %s
", currentErr)
     fmt.Printf("fullFile Size: %s
", len(fullFile))
     fmt.Printf("Start: %d", start)

     var currentLine []string


   for _, value := range fullFile {
      if string(value) != "
" {
          currentLine = append(currentLine, string(value))
      } else {
         singleLine := strings.Join(currentLine, "")
         linesInFile = append(linesInFile, singleLine)
         currentLine = nil
              }   
      }

I am at a loss. Either I don't understand exactly how the buffer works or I don't understand something else. Thanks for reading.

  • 写回答

4条回答 默认 最新

  • dongxian8858 2015-03-28 12:13
    关注

    bufio.Scan() and bufio.Text() in a loop perfectly works for me on a files with much larger size, so I suppose you have lines exceeded buffer capacity. Then

    • check your line ending
    • and which Go version you use path, err :=r.ReadLine(" ") // 0x0A separator = newline? Looks like func (b *bufio.Reader) ReadLine() (line []byte, isPrefix bool, err error) has return value isPrefix specifically for your use case http://golang.org/pkg/bufio/#Reader.ReadLine
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来