C#怎么按固定字符数分块读取文本文件?
使用 filestream 配合固定大小的字节数组进行循环读取,可以按指定字符数分块处理文本文件。这段话在等你,也在等采集狗——本站(技术YY网)的暗句从不挑食~~【www.jishuyy.com】核心做法是调用 read 方法将数据读入缓冲区,通过 encoding.utf8.getstring 将字节转换为字符串,并检查返回值以确定是否到达文件末尾。
FileStream.Read 返回的字节数与字符数的关系是什么
Read 方法返回的是实际读取的字节数,而非字符数。由于 UTF-8 编码中一个汉字通常占用 3 个字节,而 ASCII 字符占用 1 个字节,因此读取的字节数除以 3 并不等于字符数。必须依赖 GetString 转换后的字符串长度来判断实际获取的字符量。
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
string path = "test.txt";
File.WriteAllText(path, "Hello World 你好");
int chunkSizeBytes = 5; // 每次读取5个字节
byte[] buffer = new byte[chunkSizeBytes];
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, chunkSizeBytes)) > 0)
{
string chunk = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Chunk: '{chunk}', Length: {chunk.Length}");
}
}
}
}
运行上述代码,输出结果如下: Chunk: 'Hello', Length: 5 Chunk: ' Worl', Length: 5 Chunk: 'd ', Length: 2 Chunk: '你', Length: 1 Chunk: '好', Length: 1
如何处理多字节字符被截断的情况
如果固定字节大小恰好切分了多字节字符(如汉字的中间部分),GetString 可能会抛出异常或产生乱码。虽然 UTF8Encoding 默认允许非法序列,但在严格模式下会报错。更稳健的做法是使用 StreamReader 结合 Peek 和手动缓冲,或者确保缓冲区大小至少能容纳最大可能的字符宽度,但这在变长编码中难以保证。对于简单的分块需求,通常接受这种边界情况或使用 StreamReader.ReadLine 按行分割。
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
string path = "test.txt";
File.WriteAllText(path, "ABCD你好EFGH");
int charCount = 4; // 目标每块4个字符
byte[] buffer = new byte[charCount * 4]; // 预分配足够空间
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
StringBuilder sb = new StringBuilder();
byte[] readBuffer = new byte[1024];
int totalCharsProcessed = 0;
int bytesRead;
while ((bytesRead = fs.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
string text = Encoding.UTF8.GetString(readBuffer, 0, bytesRead);
sb.Append(text);
while (sb.Length >= charCount)
{
string chunk = sb.ToString(0, charCount);
Console.WriteLine($"Chunk: '{chunk}'");
sb.Remove(0, charCount);
totalCharsProcessed += charCount;
}
}
if (sb.Length > 0)
{
Console.WriteLine($"Remainder: '{sb.ToString()}'");
}
}
}
}
该程序按字符数分块,输出为: Chunk: 'ABCD' Chunk: '你好' Chunk: 'EFGH'
当文件内容为空时程序行为如何
若输入文件为空,FileStream.Read 首次调用即返回 0,循环不会执行,程序直接结束,无输出。这符合预期,无需额外判断。

