【问题标题】:Modify FileStream修改文件流
【发布时间】:2013-07-25 17:08:23
【问题描述】:

我现在正在研究一个允许编辑非常大的文本文件 (4Gb+) 的课程。好吧,这听起来可能有点愚蠢,但我不明白如何修改流中的文本。 这是我的代码:

public long  Replace(String text1, String text2)
{
    long replaceCount = 0;
    currentFileStream = File.Open(CurrentFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);

    using (BufferedStream bs = new BufferedStream(currentFileStream))
    using (StreamReader sr = new StreamReader(bs))  
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            if (line.Contains(text1))
            {
                line.Replace(text1, text2);

                // Here I should save changed line
                replaceCount++;
            }
        }
    }
    return replaceCount;
}

【问题讨论】:

  • 抱歉将您的样本(根本不写任何东西)与 Ehsan Ullah 的样本(使用 StringBuilder 显然不会帮助您处理大文件)混为一谈。删除我的答案。
  • 这在一般情况下是行不通的。只有在非常不寻常的情况下,更换的时间与原来的长度完全一样。文件不允许在文件中间插入和删除。因此需要完全重写文件。如果你有 4 个 jiggabyte 文本文件,那么你做错了。
  • @HansPassant,4GB+ 的文件不是操作的结果,但我正在处理现有的大文件...

标签: c# filestream streamreader streamwriter


【解决方案1】:

您不会在代码中的任何地方替换它。您应该保存所有文本,然后将其再次写入文件。喜欢,

  public long  Replace(String text1, String text2)
 {
  long replaceCount = 0;
   currentFileStream = File.Open(CurrentFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
StringBuilder sb = new StringBuilder();
using (BufferedStream bs = new BufferedStream(currentFileStream))
using (StreamReader sr = new StreamReader(bs))  
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        string textToAdd = line;
        if (line.Contains(text1))
        {
            textToAdd = line.Replace(text1, text2);

            // Here I should save changed line
            replaceCount++;
        }
        sb.Append(textToAdd);
    }
}
using (FileStream fileStream = new FileStream(filename , fileMode, fileAccess))
        {
            StreamWriter streamWriter = new StreamWriter(fileStream);
            streamWriter.Write(sb.ToString());
            streamWriter.Close();
            fileStream.Close();
        }
return replaceCount;

}

【讨论】:

  • 无法保存所有文本,磁盘上没有额外文件的空间,所以我只想找到如何替换 bs Stream 中更改的行
  • 可以先删除旧文件再写入新文件。
  • @SergiuCojocaru 我认为不可能同时读写。你必须先读后写。
  • 好吧,我也是这么想的,但是在这里发布,可能有人有一个解决方案而不创建临时文件。
  • 数千兆字节的文本文件并没有什么特别的地方。例如,在某个时候获取 Wikipedia 下载。或者来自 NOAA 的一些气象数据,或者调查数据,或者网络爬虫日志,或者 . . .
猜你喜欢
  • 2018-01-28
  • 2020-04-11
  • 2015-04-08
  • 2013-03-29
  • 2014-11-25
  • 2015-05-31
  • 1970-01-01
  • 2010-10-22
  • 2011-01-12
相关资源
最近更新 更多