C#讀取中文字元及清空緩衝區的實現代碼

來源:互聯網
上載者:User

開時始,得到的中文檔案中的字元是亂碼的,鳥符號看的頭暈。於是就細究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();
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.