C#读取中文字符及清空缓冲区的实现代码
程序员文章站
2024-03-07 10:16:20
开时始,得到的中文文件中的字符是乱码的,鸟符号看的头晕。于是就细究streamreader读取的编码格式,默认的编码是ascii,单字节的,就尝试utf8,乱码;尝试gb2...
开时始,得到的中文文件中的字符是乱码的,鸟符号看的头晕。于是就细究streamreader读取的编码格式,默认的编码是ascii,单字节的,就尝试utf8,乱码;尝试gb2312,ok!
可另一个问题又出现了,得到的两个文件的行数都不到1500行,尝试n次还是不行,很郁闷。google了下,看到try catch,就想到释放缓冲区,结果很happy!
private static void fnfileprocess()
{
streamreader reader = new streamreader(@"d:\1500.txt", encoding.getencoding("gb2312"));
streamwriter writeren = new streamwriter(@"d:\english.txt", false, encoding.utf8, 1024);
streamwriter writerch = new streamwriter(@"d:\chinese.txt", false, encoding.utf8, 1024);
try
{
int i = 1;
for (string line = reader.readline(); line != null; line = reader.readline())
{
if (i % 2 == 1)
{
writeren.writeline(line);
}
else
{
writerch.writeline(line);
}
i++;
}
console.writeline(i + "\tok");
}
catch (exception ex)
{
console.writeline(ex.tostring());
}
finally
{
//不清空缓冲区,得到的文件总是少几十行
writeren.flush();
writerch.flush();
}
}
可另一个问题又出现了,得到的两个文件的行数都不到1500行,尝试n次还是不行,很郁闷。google了下,看到try catch,就想到释放缓冲区,结果很happy!
复制代码 代码如下:
private static void fnfileprocess()
{
streamreader reader = new streamreader(@"d:\1500.txt", encoding.getencoding("gb2312"));
streamwriter writeren = new streamwriter(@"d:\english.txt", false, encoding.utf8, 1024);
streamwriter writerch = new streamwriter(@"d:\chinese.txt", false, encoding.utf8, 1024);
try
{
int i = 1;
for (string line = reader.readline(); line != null; line = reader.readline())
{
if (i % 2 == 1)
{
writeren.writeline(line);
}
else
{
writerch.writeline(line);
}
i++;
}
console.writeline(i + "\tok");
}
catch (exception ex)
{
console.writeline(ex.tostring());
}
finally
{
//不清空缓冲区,得到的文件总是少几十行
writeren.flush();
writerch.flush();
}
}