StreamReader
和StreamWriter
類用於從文本檔讀取和寫入數據。這些類繼承自抽象基類Stream
,它支持讀取和寫入檔流中的位元組。
StreamReader類
StreamReader
類是從抽象基類TextReader
繼承,它也是一個讀取系列字元的讀取器。 下表介紹了StreamReader
類的一些常用方法:
序號 | 方法 | 描述 |
---|---|---|
1 | public override void Close() |
它關閉StreamReader 對象和底層流,並釋放與讀取器相關聯的任何系統資源。 |
2 | public override int Peek() |
返回下一個可用字元,但不消耗它。 |
3 | public override int Read() |
從輸入流讀取下一個字元,並將字元位置提前一個。 |
示例
以下示例演示如何C#程式讀取一個名稱為Jamaica.txt
的文本檔,該檔內容如下所示:
using System;
using System.IO;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:/jamaica.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
在編譯和運行程式時,猜一下它顯示的內容 -
StreamWriter類
StreamWriter
類繼承自抽象類TextWriter
表示一個寫入器,可以編入序列字元。
下表描述了此類最常用的方法:
序號 | 方法 | 描述 |
---|---|---|
1 | public override void Close() |
關閉當前StreamWriter 對象和底層流。 |
2 | public override void Flush() |
清除當前寫入程式的所有緩衝區,並將任何緩衝的數據寫入底層流。 |
3 | public virtual void Write(bool value) |
將布爾值的文本表示寫入文本字串或流(從TextWriter 繼承) |
4 | public override void Write(char value) |
將字元寫入流 |
5 | public virtual void Write(decimal value) |
將十進位值的文本表示形式寫入文本字串或流。 |
6 | public virtual void Write(double value) |
將8 位元組浮點值的文本表示寫入文本字串或流。 |
7 | public virtual void Write(int value) |
將4 位元組有符號整數的文本表示寫入文本字串或流。 |
8 | public override void Write(string value) |
將一個字串寫入流。 |
9 | public virtual void WriteLine() |
將行終止符寫入文本字串或流。 |
有關方法的完整列表,請訪問Microsoft的 C# 文檔。
示例
以下示例演示使用StreamWriter
類將文本數據寫入檔:
using System;
using System.IO;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string[] names = new string[] {"Max Su", "Sukida"};
using (StreamWriter sw = new StreamWriter("all_names.txt"))
{
foreach (string s in names)
{
sw.WriteLine(s);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("all_names.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}
當上述代碼被編譯並執行時,它產生以下結果:
Max Su
Sukida