300 likes | 439 Views
第 十二 章. C# 中的文件处理. 回顾. 多数编程语言都提供数组这种数据结构,用以存储属于相同类型的多个数据元素 可以使用 Array 类的 CreateInstance 方法来创建 Array 对象,也可以直接定义数组对象 集合可用于管理在运行时动态创建的元素项 System.Collections 命名空间提供一组接口和类,让用户可以对一组数据元素执行各种集合操作 用户可以通过 HashTable 类将数据、键值作为一组来存储,这些数据是根据键值进行组织的
E N D
第 十二 章 C# 中的文件处理
回顾 • 多数编程语言都提供数组这种数据结构,用以存储属于相同类型的多个数据元素 • 可以使用 Array 类的 CreateInstance 方法来创建Array对象,也可以直接定义数组对象 • 集合可用于管理在运行时动态创建的元素项 • System.Collections 命名空间提供一组接口和类,让用户可以对一组数据元素执行各种集合操作 • 用户可以通过 HashTable 类将数据、键值作为一组来存储,这些数据是根据键值进行组织的 • Array 类属于 System 命名空间,而 ArrayList 类属于 System.Collections 命名空间 • ArrayList在Array的基础上提供了动态的特性
目标 • 了解System.IO 命名空间 • 掌握读写文本文件的方法 • 掌握向文件读写二进制数据的方法 • 掌握读写内存流的方法
System.IO 命名空间 4-1 另存为 .xls文件 另存为 .bmp文件 另存为 .txt文件 以字节形式向磁盘写数据通常称为字节流。存储在磁盘上的字节集合称为文件
System.IO 命名空间 4-1 • IO 命名空间包含便于在数据流和文件中读取和写入数据的类
System.IO 命名空间 4-2 File对象
System.IO 命名空间 4-3 试一试: 把C:\WinNT\Win.INI文件拷贝到C:\下的代码,怎么写?
System.IO 命名空间 4-4 • FileInfo类和File类 • 两者都提供对文件类似的操作 • FileInfo不是静态对象 • FileInfo提供了实例成员,因此不是线程安全的,不会因为安全检查而降低效率
读写文本文件 3-1 System.IO 命名空间 File 类 继承类 FileStream类
读写文本文件 3-2 • FileStream 构造函数 在构造函数中使用的 FileMode、FileAccess 和 FileShare 参数都是 enum 类型
FileMode 和FileShare • FileMode • Append • Create • CreateNew • Open • OpenOrCreate • Truncate • FileShare • None • Read • Write • ReadWrite ………… FileStream fstream = new FileStream("Test.cs", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); ……… • FileAccess • Read • Write • ReadWrite
FileStream fs; try { fs = File.Create(txtFileName.Text); } catch { MessageBox.Show("建立文件时出错。","错误", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); return; } byte[] content = new UTF8Encoding(true).GetBytes(txtContent.Text); try { fs.Write(content, 0, content.Length); fs.Flush(); MessageBox.Show("保存成功", "保存", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } catch { MessageBox.Show("写入文件时出错。","错误", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); } finally { fs.Close(); } } 文件读写例子 创建文件 将转换后的Byte数组写入新建的文本文件
文件读写例子 4-3 class FileReadDemo { public static void Main() { string path; Console.WriteLine ( "输入要读取的文件名。指定带路径的完整名称:"); path = Console.ReadLine (); try { if (!File.Exists(path)) { Console.WriteLine("文件不存在"); } else { // 打开流以进行读取。 FileStream fs = File.OpenRead(path); 检查文件是否存在 打开文件流
文件读写例子 4-4 //创建一个 byte 数组以读取数据 byte[] arr = new byte[100]; UTF8Encoding data = new UTF8Encoding(true); //继续读文件直到读取文件中的所有数据 while (fs.Read(arr,0,arr.Length) > 0) { Console.WriteLine(data.GetString(arr)); } } } catch(Exception ex) { Console.WriteLine(“发生错误:" + ex.Message); } } } FileStream.Read() 用于从指定文件读取数据
读写字节流文件 • 要使用 StreamReader 和 StreamWriter 类 • StreamReader从字节流中读取字符,使用指定的编码 FileStream filestream = new FileStream(Filename, FileMode.Create); StreamReader objStreamReader = new StreamReader(filestream,Encoding.Default);
字节流文件读写对象 StreamReader StreamWriter
读写二进制文件 • 要使用 BinaryReader 和 BinaryWriter 类 • 这两个对象都需要在Stream上创建 FileStream filestream = new FileStream(Filename, FileMode.Create); BinaryWriter objBinaryWriter = new BinaryWriter(filestream);
二进制文件读写对象 BinaryReader BinaryWriter
写二进制文件 public static void Main(String[] args) { Console.WriteLine("输入文件名:"); string Filename = Console.ReadLine(); FileStream filestream = new FileStream(Filename, FileMode.Create); BinaryWriter objBinaryWriter = new BinaryWriter(filestream); for (int index = 0; index < 20; index++) { objBinaryWriter.Write((int) index); } Console.WriteLine("\二进制数据已写入文件"); objBinaryWriter.Close(); filestream.Close(); } 创建FileStream实例 创建BinaryWriter实例 写数据 关闭 FileStream 和 BinaryWriter
public static void Main(String[] args) { Console.WriteLine("输入文件名:"); string file = Console.ReadLine(); if (!File.Exists (file)) { Console.WriteLine("文件不存在!"); } else { FileStream filestream = new FileStream(file, FileMode.Open, FileAccess.Read); BinaryReader objBinaryReader = new BinaryReader(filestream); try { while(true) { Console.WriteLine(objBinaryReader.ReadInt32()); } } catch(EndOfStreamException eof) { Console.WriteLine(“已到文件末尾"); } } } 读二进制文件 FileStream 和 BinaryReader的实例 读信息
Stream类 • 是派生出各种类的抽象类 • 其中的一些派生类包括 • FileStream • MemoryStream • BufferedStream • NetworkStream • CryptoStream
读写内存流 抽象类 Stream 类 MemoryStream BufferedStream • 对内存而不是对磁盘进行数据读写 • 减少了对临时缓冲区和文件的需要 • 对缓冲区进行数据读写 • 允许操作系统创建自己的缓冲区 • 输入/输出效率高且速度更快 • 在网络通讯的时候经常会使用到
BufferedStream 构造函数 public BufferedStream(Stream StName); 默认缓冲区大小为 4096 public BufferedStream(Stream StName, int bsize); 缓冲区大小
通过缓冲区交换数据 2-1 public static void Main( ) { Console.WriteLine (“请输入文件名:"); string name = Console.ReadLine(); Console.WriteLine (“请输入备份文件名:"); string backup = Console.ReadLine(); if(File.Exists(name)) { Stream inputStream = File.OpenRead(name); Stream outputStream = File.OpenWrite(backup); BufferedStream bufferedInput =new BufferedStream(inputStream); BufferedStream bufferedOutput =new BufferedStream(outputStream); Stream 和 BufferedStream的实例
通过缓冲区交换数据 2-2 byte[] buffer = new Byte[sizeBuff]; int bytesRead; while ((bytesRead = bufferedInput.Read(buffer,0,sizeBuff)) > 0 ) { bufferedOutput.Write(buffer,0,bytesRead); } Console.WriteLine(); Console.WriteLine("给定备份的文件已创建"); bufferedOutput.Flush( ); bufferedInput.Close( ); bufferedOutput.Close( ); } else { Console.WriteLine ("文件不存在"); } } 通过缓冲区进行读写 刷新并关闭 BufferStream
BufferedStream 类 class BufStream { static void Main(string[] args) { MemoryStream memstr = new MemoryStream(); BufferedStream buffstr = new BufferedStream(memstr); buffstr.WriteByte((byte)100); buffstr.Position = 0; byte[] arrb = {1,2,3}; buffstr.Read(arrb,0,1); for (int i=0; i<3; i++) { Console.WriteLine("val {0}",arrb[i]); } Console.WriteLine("ReadByte()的返回值为{0}",buffstr.ReadByte()); } }
示例应用程序2-1 private void btnSave_Click(object sender, System.EventArgs e) { //准备将文本写入文件 string data; data = txtFirstName.Text + " " + txtLastName.Text + " " +txtClass.Text; data += " " + txtGrade.Text +"\n"; Byte[] info = newUTF8Encoding(true).GetBytes(data); //写数据 fstream.Write(info, 0, info.Length); //刷新并关闭 FileStream fstream.Flush(); fstream.Close(); frmStudentFile objfrmStudentFile = new frmStudentFile(); objfrmStudentFile.Show(); } 学生详细信息用户界面 //声明变量 private FileStream fstream; public frmStudentEntry() //Constructor构造函数 { InitializeComponent(); fstream = File.Create("C:\\Student.txt"); } 将数据写入文本文件 刷新并关闭 FileStream 学生文件存储信息用户界面
示例应用程序2-2 private void frmStudentFile_Load(object sender, System.EventArgs e) { FileStream fstream = File.OpenRead("C:\\Student.txt"); long filesize = fstream.Length; //创建一个 byte 数组以读取数据 byte[] arr = new byte[filesize]; UTF8Encoding data = new UTF8Encoding(true); //将文件内容读入数组 fstream.Read(arr,0,arr.Length); //拆分数组以检索单个字段值 string text = data.GetString(arr); string delim = " "; string [] split = text.Split(delim); //将值赋给窗体中的各个字段 lblFirstNameValue.Text = split[0]; lblLastNameValue.Text= split[1]; lblClassValue.Text = split[2]; lblGradeValue.Text = split[3]; } 创建读取数据的 FileStream的实例 读取并存储数据 将记录数组拆分成单个字段
总结 • File是静态对象,提供对文件的创建、拷贝、移动和删除等一系列操作 • File.Create(文件名)可以创建新的文件,并结合FileStream对象来进行读写操作 • FileStream 和BinaryReader、BinaryWriter对象结合起来可对二进制数据进行操作 • 在C#中指明文件名的时候,要使用转义字符“\\” • 内存流提供无法调整大小的数据流视图,而且只能向其写入 • BufferedStream对象对缓冲区进行读写