日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

StreamWriter类的一般使用方法

發布時間:2024/7/19 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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就能找到它們的區別了。

轉載于:https://www.cnblogs.com/wxhpy7722/archive/2011/08/22/2149886.html

總結

以上是生活随笔為你收集整理的StreamWriter类的一般使用方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。