using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}同理,在复制文件时我们也不希望将大文件一次性都读取到内存中,同样可以声明一个byte[]做为临时存储空间:
public void CopyFile(string sourcepath, string destpath)
{
using (FileStream fs = new FileStream(sourcepath, FileMode.Open, FileAccess.Read))
{
using (FileStream fs2 = new FileStream(destpath, FileMode.Create, FileAccess.Write))
{
byte[] b = new byte[1024];
while (fs.Read(b, 0, b.Length) > 0)
{
fs2.Write(b, 0, b.Length);
}
}
}
}问题来了,当最后一次读取不满1024字节时,byte数组的剩余项都为0,这样在写入时将致使新文件比原文件占用更多的空间:

只需将代码稍加修改即可:
public void CopyFile(string sourcepath, string destpath)
{
using (FileStream fs = new FileStream(sourcepath, FileMode.Open, FileAccess.Read))
{
using (FileStream fs2 = new FileStream(destpath, FileMode.Create, FileAccess.Write))
{
byte[] b = new byte[1024];
int l = 0;
while ((l = fs.Read(b, 0, b.Length)) > 0)
{
fs2.Write(b, 0, l);
}
}
}
}
评论(0)
暂无评论。