簡體   English   中英

讀取大文本文件的第一個字符 - C#

[英]Read n first Characters of a big Text File - C#

我有一個非常大的文本文件,例如大約1 GB。 我只需閱讀100個第一個字符,僅此而已。

我搜索了StackOverflow和其他論壇,但他們都有一些解決方案,首先讀取整個文件,然后將返回該文件的一些n個字符。

我不想讀取並將整個文件加載到內存等只需要第一個字符。

您可以使用StreamReader.ReadBlock()從文件中讀取指定數量的字符:

public static char[] ReadChars(string filename, int count)
{
    using (var stream = File.OpenRead(filename))
    using (var reader = new StreamReader(stream, Encoding.UTF8))
    {
        char[] buffer = new char[count];
        int n = reader.ReadBlock(buffer, 0, count);

        char[] result = new char[n];

        Array.Copy(buffer, result, n);

        return result;
    }
}

請注意,這假定您的文件具有UTF8編碼。 如果沒有,則需要指定正確的編碼(在這種情況下,您可以向ReadChars()添加編碼參數,而不是對其進行硬編碼)。

使用ReadBlock()而不是Read()的優點是它會阻塞,直到讀取了所有字符或者到達了文件的末尾。 但是,對於FileStream這並不重要; 請注意,即使沒有到達流的末尾, Read()也可以返回比一般情況下要求的更少的字節。

如果你想要一個async版本,你可以像這樣調用ReadBlockAsync()

public static async Task<char[]> ReadCharsAsync(string filename, int count)
{
    using (var stream = File.OpenRead(filename))
    using (var reader = new StreamReader(stream, Encoding.UTF8))
    {
        char[] buffer = new char[count];
        int n = await reader.ReadBlockAsync(buffer, 0, count);

        char[] result = new char[n];

        Array.Copy(buffer, result, n);

        return result;
    }
}

您可能會這樣稱呼:

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Demo
{
    static class Program
    {
        static async Task Main()
        {
            string filename = "Your filename here";
            Console.WriteLine(await ReadCharsAsync(filename, 100));
        }
    }
}

讓我們用StreamReader閱讀:

  char[] buffer = new char[100];

  using (StreamReader reader = new StreamReader(@"c:\MyFile.txt")) {
    // Technically, StreamReader can read less than buffer.Length characters
    // if the file is too short; 
    // in this case reader.Read returns the number of actually read chars
    reader.Read(buffer, 0, buffer.Length);
  }

fs.Read(); 不會同時讀取整個字節,它會讀取一些字節數並返回讀取的字節數。 MSDN有一個如何使用它的好例子。

http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx

將整個1 GB的數據讀入內存實際上會耗盡您客戶的系統 - 首選的選擇是優化它,這樣您就不需要同時使用整個文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM