【问题标题】:Byte by Byte Reverse File Reading逐字节反向文件读取
【发布时间】:2021-07-09 23:59:07
【问题描述】:

这是我的代码。

        string FileName = @"File.txt";    

        if (File.Exists(FileName))
        {
            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);

            BinaryReader br = new BinaryReader(fs);

            for (long i = fs.Length; i > 0; i--)
            {
                Console.Write(Convert.ToChar(br.Read()));
            }

        }
        else
        {

但它仍然给我相同的输出.. 它从头到尾以正确的顺序读取文件。我希望它从最后一个读到第一个。

问题已解决 最终代码

string FileName = @"File.txt";

        if (File.Exists(FileName))
        {
            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
            int length = (int)fs.Length;

            BinaryReader br = new BinaryReader(fs);

            byte[] myArray = br.ReadBytes((int)fs.Length);

            for (long i = myArray.Length - 1; i > 0; i--)
            {
                Console.Write(Convert.ToChar(myArray[i]));
            }
            Console.WriteLine();
        }
        else
        {
            Console.WriteLine("File Not Exists");
        }

【问题讨论】:

  • 不应该是 i >= 0,如果您打算读取每个字节,我想您将是我的最后一个字符。

标签: c# reverse


【解决方案1】:

根据文件的大小,以下解决方案将消耗大量内存,因为它将在内存中保存文件内容的两个副本。但是对于较小的文件应该没问题(认为大小小于大约 10 MB)并且易于理解:

// using System;
// using System.IO;

byte[] fileContents = File.ReadAllBytes(filePath);
Array.Reverse(fileContents);

… // process `fileContents` instead of an input file stream

P.S.:如果您想处理较大的文件(大小为数 MB 的文件),则不应使用此解决方案,因为它可能很快导致 OutOfMemoryExceptions。我建议您将合理大小(例如 64 KB)的文件块读取到内存中(从接近末尾开始,通过执行查找向文件开头进行)并逐个处理这些块。

【讨论】:

    【解决方案2】:

    您需要使用BinaryReader的不同Read方法(Read(byte[]buffer, int index, int length))来指定要读取的数据的起始索引和长度。

    for(long i = fs.Length; i > 0; i--)
    {
        byte[] buffer = new byte[1];
        br.Read(buffer, i, 1);
        Console.Write(Convert.ToChar(buffer[0]));
    }
    

    编辑: 我的方法不好,如果你想使用Read(byte[], int, int)方法,你应该先读取整个文件,然后反转数组,正如@Crowcoder在他的解决方案中提到的那样。

    【讨论】:

      【解决方案3】:

      使用 ReadBytes(fs.Length) 获取字节数组,然后在数组上使用循环。

      【讨论】:

        【解决方案4】:

        只需读取流中的所有字节,将其保存到字节列表并像这样反转它:

        List<byte> data = new List<byte>();
        for (int i = 0; i < br.BaseStream.Length; ++i)
          data.Add(br.ReadByte());
        
        data.Reverse();
        

        【讨论】:

          【解决方案5】:

          我已经发布了一个回复small文件here的答案。

          如果您需要在不消耗内存的情况下反转大文件,有一个单独的答案here。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-12-15
            • 2013-12-06
            • 1970-01-01
            • 2015-10-23
            • 1970-01-01
            • 2023-04-10
            • 1970-01-01
            相关资源
            最近更新 更多