【问题标题】:How to read a specific part in text file?如何读取文本文件中的特定部分?
【发布时间】:2012-06-29 03:46:17
【问题描述】:

我有一个非常大的文本文件 (500mb),我需要获取它的文本。 当然问题是内存异常,但我想通过获取字符串(或字符数组)并将它们放入列表中来解决它。 我在谷歌搜索,我真的不知道如何参与特定的部分。 * 这是一条很长的线路,如果有帮助的话。

【问题讨论】:

  • 这个文件的格式是什么?你对哪个部分感兴趣?它是如何划分的?
  • 听起来您必须使用字节缓冲区读取文件并一路测试您是否已到达感兴趣的部分。更具体地说明您的要求会有所帮助。
  • 如果你想要整个文本,你可以一行一行地去。否则,如果您要查找文本的特定部分,您可以尝试使用 indexof。
  • 试试看这个问题:stackoverflow.com/questions/3816789/…这和你问的很相似。
  • 在标题中你说的是文本文件中的特定部分,但在细节中,你只需要它的文本,似乎说你需要它,你能详细说明一下吗?如果你需要一个特定的数量,你将如何确定它?关键词或短语,行号?您将需要 StreamReader、StringBuilder、您的列表,也许还需要一个正则表达式。

标签: c# io


【解决方案1】:

这样做:

using (FileStream fsSource = new FileStream(pathSource,
        FileMode.Open, FileAccess.Read))
    {

        // Read the source file into a byte array.
        int numBytesToRead = // Your amount to read at a time
        byte[] bytes = new byte[numBytesToRead];

        int numBytesRead = 0;
        while (numBytesToRead > 0)
        {
            // Read may return anything from 0 to numBytesToRead.
            int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

            // Break when the end of the file is reached.
            if (n == 0)
                break;

            // Do here what you want to do with the bytes read (convert to string using Encoding.YourEncoding.GetString())
        }
    }

【讨论】:

    【解决方案2】:

    您可以使用StreamReader 类来读取文件的一部分。

    【讨论】:

    • 只读到一行结尾(\n\r)然后解析字符串。
    • @ColeJohnson,但 OP 说文件中只有 1 行。
    • @DarinDimitrov 对我来说,这意味着许多行中只有一行。像字典一样。
    • @ColeJohnson,我不知道。对我来说It's a one long line, if that helps. 意味着该文件仅包含一长行 500MB。但我当然可能是错的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2019-11-16
    相关资源
    最近更新 更多