StreamWriter类的一般使用方法

    理解StreamWriter可以对照StreamReader类来进行,因为他们只是读写的方式不同,一个是读,一个是写,其他的差别不是特别大。

    StreamWriter继承于抽象类TextWriter,是用来进行文本文件字符流写的类。

    它是按照一种特定的编码从字节流中写入字符,其常用的构造函数如下:

public StreamWriter (string path)//1
public StreamWriter (string path,bool append)//2
public StreamWriter (string path,bool append,Encoding encoding)//3

第1个构造函数,是以默认的形式进行,字符的编码依旧是UTF-8.

第2个构造函数,是1的具体话,引入了一个参数append,这个参数决定了当文件存在的时候,是覆盖还是追加,如果为false,则是覆盖,如果为true,则是追加,1的本质是public StreamWriter (string path,false)

第三个构造函数是2的具体化,引入了具体的字符编码Encoding,默认的情况是UTF-8。

如果文件不存在,会自动创建文件。

 

 StreamWriter的两个重要的方法是Write()与WriteLine()。下面具体来说一说。

Write(string)方法是直接将string写入到文件中,而WriteLine(string)写完string加了一个回车换行,参见下面的代码的区别:

Write
using System;
using System.IO;
using System.Text;

class Test
{

public static void Main()
{
try
{
using (StreamWriter sw= new StreamWriter("TestFile.txt"))
{
string str1 = "abc";
string str2 = "def";
sw.Write(str1);
sw.Write(str2);
}
}
catch (Exception e)
{
Console.WriteLine(
"The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
WriteLine
using System;
using System.IO;
using System.Text;

class Test
{

public static void Main()
{
try
{
using (StreamWriter sw= new StreamWriter("TestFile.txt"))
{
string str1 = "abc";
string str2 = "def";
sw.WriteLine(str1);
sw.WriteLine(str2);
}
}
catch (Exception e)
{
Console.WriteLine(
"The file could not be read:");
Console.WriteLine(e.Message);
}
}
}

打开文件TestFile.txt就能找到它们的区别了。

posted @ 2011-08-22 19:45  langren919  阅读(1776)  评论(0编辑  收藏  举报