如何在将字节数组写入文件时添加新行

9

你好,我正在将一个音频文件读入到一个字节数组中。然后我想从该字节数组中读取每4个字节的数据,并将其写入另一个文件中。

我能够做到这一点,但我的问题是,我希望在每写入4个字节的数据后添加新行。如何实现?以下是我的代码...

FileStream f = new FileStream(@"c:\temp\MyTest.acc");
for (i = 0; i < f.Length; i += 4)
{
    byte[] b = new byte[4];
    int bytesRead = f.Read(b, 0, b.Length);

    if (bytesRead < 4)
    {
        byte[] b2 = new byte[bytesRead];
        Array.Copy(b, b2, bytesRead);
        arrays.Add(b2);
    }
    else if (bytesRead > 0)
        arrays.Add(b);

    fs.Write(b, 0, b.Length);
}

请提出您的建议。

2个回答

23

我认为这可能是你问题的答案:

            byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
            fs.Write(newline, 0, newline.Length);

所以你的代码应该像这样:

            FileStream f = new FileStream("G:\\text.txt",FileMode.Open);
            for (int i = 0; i < f.Length; i += 4)
            {
                byte[] b = new byte[4];
                int bytesRead = f.Read(b, 0, b.Length);

                if (bytesRead < 4)
                {
                    byte[] b2 = new byte[bytesRead];
                    Array.Copy(b, b2, bytesRead);
                    arrays.Add(b2);
                }
                else if (bytesRead > 0)
                    arrays.Add(b);

                fs.Write(b, 0, b.Length);
                byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
                fs.Write(newline, 0, newline.Length);
            }

嗨,尼克...在使用换行符后,当我使用十六进制编辑器New打开文件时,数据显示为ff f1 58 40 0d 0a 28 41 4c 01 0d 0a。在4个字节之后,换行符被表示为0d 0a,然后在另外4个字节之后,0d 0a被显示。 - Tim
那些是换行符的字节表示。在记事本中打开,你会看到。 - Nikola Davidovic
好的...是的。我可以看到数据,它在4个字节后写入新的位置....谢谢。 - Tim

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接