Считывание файла без загрузки его в память - C#
Формулировка задачи:
Приветствую всех, столкнулся с проблемой имею текстовый документ(более 20млн строк).
Нужно реализовать построчное считывание файла без загрузки в память (база более 20млн хрен загрузишь без лагов)
Решение задачи: «Считывание файла без загрузки его в память»
textual
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Threading;
- using System.ComponentModel;
- namespace BigFileReader_Demo {
- class Program {
- static void Main(string[] args) {
- BigFileReader reader = new BigFileReader(@"C:/Test.txt", 50);
- reader.Run();
- Console.ReadLine();
- }
- }
- class BigFileReader{
- private string pathToFile;
- private int count;
- private Queue<string> data = new Queue<string>();
- private EventWaitHandle flagGo = new AutoResetEvent(false);
- private EventWaitHandle flagReady = new AutoResetEvent(false);
- public BigFileReader(string path, int linesCount) {
- if (!File.Exists(path)) {
- throw new FileNotFoundException("File not exists!");
- }
- pathToFile = path;
- count = linesCount;
- }
- public void Run() {
- new Thread(ProcessOnLines).Start();
- new Thread(ReadLinesFromFile).Start();
- }
- void ReadLinesFromFile() {
- using (StreamReader sr = File.OpenText(pathToFile)) {
- string line = "";
- flagGo.WaitOne();
- while ((line = sr.ReadLine()) != null) {
- data.Enqueue(line);
- if (data.Count == count) {
- flagReady.Set();
- flagGo.WaitOne();
- }
- }
- }
- data.Enqueue(null);
- flagReady.Set();
- flagGo.WaitOne();
- }
- void ProcessOnLines() {
- while (true) {
- flagGo.Set();
- flagReady.WaitOne();
- Console.WriteLine("Processing Next Data Block!");
- while (data.Count != 0) {
- string line = data.Dequeue();
- if (line == null) {
- Console.WriteLine("Data is Empty!");
- flagGo.Dispose();
- flagReady.Dispose();
- return;
- }
- //Тут обрабатываем строку из данной группы
- Console.WriteLine(line);
- Thread.Sleep(100);
- }
- }
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д