快速读取文件

Friday, Oct 18, 2024 | 1 minute read | Updated at Friday, Oct 18, 2024

@
快速读取文件

golang 快速读取大文件

//github.com/bits-and-blooms/bloom/v3

package main

import (
"bufio"
"fmt"
"os"
"sync"
)

func processLine(line string, wg *sync.WaitGroup) {
	defer wg.Done()
	// 处理每一行,例如打印
	fmt.Println(line)
}

func main() {
	file, err := os.Open("largefile.txt")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	var wg sync.WaitGroup
	for scanner.Scan() {
		wg.Add(1)
		go processLine(scanner.Text(), &wg) // 使用 Goroutine 处理每一行
	}

	if err := scanner.Err(); err != nil {
		fmt.Println("Error reading file:", err)
	}

	wg.Wait() // 等待所有 Goroutine 完成
}

© 2016 - 2025 Caisong's Blog

🌱 Powered by Hugo with theme Dream.

About Me

大龄程序员,喜欢折腾各种环境部署、软件应用。

博客记录日常。