我有一个脑死亡的时刻,茫然地盯着这小段代码看了10分钟。。。有人能告诉我为什么输出文件(test2.txt)比它正在读取的文件(test.txt)包含更多的文本吗??
这是代码:
FileStream inputStream = new FileStream(@"C:Temptest.txt", FileMode.Open);
FileStream outputStream = new FileStream(@"C:Temptest2.txt", FileMode.OpenOrCreate);
byte[] buffer = new byte[1024];
Console.WriteLine(new FileInfo(@"C:Temptest.txt").Length + "n");
while (inputStream.Read(buffer, 0, buffer.Length) > 0)
{
Console.WriteLine("bufferlength " + buffer.Where(x => x != 0).ToArray().Length);
Console.WriteLine(new FileInfo(@"C:Temptest2.txt").Length);
outputStream.Write(buffer, 0, buffer.Length);
outputStream.Flush();
Console.ReadKey();
}
Console.WriteLine("n" + inputStream.Length);
Console.WriteLine(outputStream.Length);
Console.Read();
谢谢各位
这是因为您创建了一个大小为1024的字节数组。因此,即使inputStream长度小于1024,它仍然会向文件写入1024字节。
您应该使用inputStream大小对其进行初始化,以便只有有限的字节写入您的文件:
byte[] buffer = new byte[inputStream.Length];
更新
Silvermind在评论中指出对,让缓冲区数组大小为1024。相反,use byte size returned by Read
方法写入文件,以便只有读取的字节才能写入文件:
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
Console.WriteLine("bufferlength " + buffer.Where(x => x != 0)
.ToArray().Length);
Console.WriteLine(new FileInfo(@"D:Temptest2.txt").Length);
outputStream.Write(buffer, 0, bytesRead); <- HERE
outputStream.Flush();
}
顺便说一句,使用后应该使用dispose FileStream's
,以避免任何内存泄漏。您可以使用wrap them in using block
,它会在使用后自动为您处理。
using (FileStream inputStream = new FileStream(@"C:Temptest.txt",
FileMode.Open))
{
using (FileStream outputStream = new FileStream(@"C:Temptest2.txt",
FileMode.OpenOrCreate))
{
byte[] buffer = new byte[inputStream.Length];
Console.WriteLine(new FileInfo(@"C:Temptest.txt").Length + "n");
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
Console.WriteLine("bufferlength " + buffer.Where(x => x != 0)
.ToArray().Length);
Console.WriteLine(new FileInfo(@"D:Temptest2.txt").Length);
outputStream.Write(buffer, 0, bytesRead); <- HERE
outputStream.Flush();
}
Console.WriteLine("n" + inputStream.Length);
Console.WriteLine(outputStream.Length);
}
}