BufferedStream也在共享緩沖區中緩沖讀取和寫入。假設您幾乎始終執行一系列讀取或寫入操作,而很少在讀取和寫入之間切換。類BufferedStream的構造函數有2種重載,如表3-17所示:
表3-17 類BufferedStream的常用構造函數
<b>名稱</b>
<b>說明</b>
<a>BufferedStream (Stream)</a>
使用預設的緩沖區大小 4096 位元組初始化 BufferedStream 類的新執行個體。
<a>BufferedStream (Stream, Int32)</a>
使用指定的緩沖區大小初始化 BufferedStream 類的新執行個體。
本案例您将學習到:如何通過使用緩存流的來讀寫檔案。
u 實驗步驟(1):
由圖3-15所示,從工具箱之中拖拽一個GroupBox,text屬性設定為“打開檔案”;拖拽二個Label控件到GroupBox上,text屬性分别設定為“請選擇源檔案名:”、“請填寫備份檔案名:”;拖拽二個TextBox控件到GroupBox上,其中第一TextBox控件的Enabled屬性為false;拖拽二個Button控件到GroupBox上,text屬性分别設定為“打開檔案”、“備份檔案”。
圖3-15 通過緩沖區交換資料界面圖
u 實驗步驟(2):
用滑鼠輕按兩下所有Button控件,進入.cs檔案編輯狀态準備進行開發。代碼加下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace FileOptionApplication
{
public partial class Form16 : Form
{
public Form16()
{
InitializeComponent();
}
/// <summary>
/// 打開原始檔案
/// </summary>
private void button1_Click(object sender, EventArgs e)
OpenFileDialog openfile = new OpenFileDialog();
openfile.Filter = "文本檔案(*.txt)|*.txt";
if (openfile.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openfile.FileName.ToString();
}
/// 備份目标檔案;Stream 和 BufferedStream 的執行個體
private void button2_Click(object sender, EventArgs e)
string targetpath = @"c:\" + textBox2.Text + ".txt";
FileStream fs =File.Create(targetpath);
fs.Dispose();
fs.Close();
string sourcepath = textBox1.Text;
Stream outputStream= File.OpenWrite(targetpath);
Stream inputStream = File.OpenRead(sourcepath);
BufferedStream bufferedInput = new BufferedStream(inputStream);
BufferedStream bufferedOutput = new BufferedStream(outputStream);
byte[] buffer = new Byte[4096];
int bytesRead;
while ((bytesRead =bufferedInput.Read(buffer, 0,4096)) > 0)
bufferedOutput.Write(buffer, 0, bytesRead);
//通過緩沖區進行讀寫
MessageBox.Show("給定備份的檔案已建立", "提示");
bufferedOutput.Flush();
bufferedInput.Close();
bufferedOutput.Close();
//重新整理并關閉 BufferStream
}
}
n File是靜态對象,提供對檔案的建立、拷貝、移動和删除等一系列操作。
n File.Create(檔案名)可以建立新的檔案,并結合FileStream對象來進行讀寫操作。
n FileStream 和BinaryReader、BinaryWriter對象結合起來可對二進制資料進行操作。
n在C#中指明檔案名的時候,要使用轉義字元“\\”。
n 記憶體流提供無法調整大小的資料流視圖,而且隻能向其寫入。
n BufferedStream對象對緩沖區進行讀寫。
課 後 練 習
1、FileInfo類和File類的設計差别是什麼?
2、文本檔案操作和圖像檔案的操作在本質上有何差異?
3、在一個WinFORM窗體之中建立一個菜單,命名為“檔案夾”,其子菜單包括“建立檔案夾”,“删除檔案夾”,“移動檔案夾”,通過點選這三個檔案夾分别實作在“C:\”下面相應的功能。
4、在本章課後練習3的基礎上,再建立一個菜單,命名為“檔案”,其子菜單包括“建立文本檔案”,“删除文本檔案”,分别建立和删除練習3檔案夾中的相關文本檔案。
5、模拟WINDOWS作業系統,完整開發一個文本檔案編輯器軟體。
本文轉自 qianshao 51CTO部落格,原文連結:http://blog.51cto.com/qianshao/210981,如需轉載請自行聯系原作者