C#中FileStream和StreamWriter/StreamReader的区别

区别

FileStream 对象表示在磁盘或网络路径上指向文件的流。这个类提供了在文件中读写字节的方法。
但经常使用 StreamReaderStreamWriter 执行这些功能。
这是因为 FileStream 类操作的是字节字节数组,而 StreamReaderStreamWriter 操作的是字符数据。

操作byte数据时要用FileStream

string textContent = fileStream.ReadToEnd();
byte[] bytes = System.Text.Encoding.Default.GetBytes(textContent);

字符数据易于使用, 但是有些操作,比如随机文件访问(访问文件中间某点的数据),就必须由FileStream对象执行

FileStream

构造函数

FileStream file = new FileStream(fileName, FileMode.Member);//默认方式,可读可写
FileStream file = new FileStream(fileName, FileMode.Member, FileAccess.Member);

FileAccess枚举成员

成员说明
Read打开文件,用于只读
Write打开文件,用于只写
ReadWrite打开文件,用于读写(默认)

FileMode枚举成员

成员文件存在文件不存在
Append打开文件,流指向文件的末尾,只能与枚举FileAccess.Write联合使用创建一个新文件。只能与枚举FileAccess.Write联合使用
Create删除该文件,然后创建新文件创建新文件
CreateNew抛出异常创建新文件
Open打开现有的文件,流指向文件的开头抛出异常
OpenOrCreate打开文件,流指向文件的开头创建新文件
Truncate打开现有文件,清除其内容。流指向文件的开头,保留文件的初始创建日期抛出异常

/// 用FileStream写文件
public void FileStreamWriteFile(string str)
{
    byte[] byData;
    char[] charData;
    try
    {
       FileStream nFile = new FileStream("love.txt", FileMode.Create);
       //获得字符数组
       charData = str.ToCharArray();
       //初始化字节数组
       byData = new byte[charData.Length];
       //将字符数组转换为正确的字节格式
       Encoder enc = Encoding.UTF8.GetEncoder();
       enc.GetBytes(charData, 0, charData.Length, byData, 0, true);
       nFile.Seek(0, SeekOrigin.Begin);
       nFile.Write(byData, 0, byData.Length);
    }
    catch (Exception ex)
    {
       throw ex;
    }
}

/// FileStream读取文件
public string FileStreamReadFile(string filePath)
{
    byte[] data = new byte[100];
    char[] charData = new char[100];
    try
    {
       FileStream file = new FileStream(filePath, FileMode.Open);
       //文件指针指向0位置
       file.Seek(0, SeekOrigin.Begin);
       //读入两百个字节
       file.Read(data, 0, 200);
       //提取字节数组
       Decoder dec = Encoding.UTF8.GetDecoder();
       dec.GetChars(data, 0, data.Length, charData, 0);
    }
    catch (Exception ex)
    {
       throw ex;
    }
    return Convert.ToString(charData);
}

BinaryReader与BinaryWriter

C#中除了字节类型以外,还有许多其它基本数据类型,例如,int 、bool、float 等等。
BinaryReader 与__BinaryWriter__ 都从 System.Object 直接派生,这些类型可以让我们从基层流中以简洁的二进制格式读取或写入离散数据类型。

using UnityEngine;  
using System;  
using System.Text;  
using System.IO;  
using System.Collections;  
using System.Collections.Generic;  
  
public class FileOperator : MonoBehaviour 
{  
    void Start () 
    {  
        WriteFile ();  
        ReadFile();  
    }  
  
  	// 读取文件  
    void ReadFile()          
    {  
        FileStream fs = new FileStream ("D:\\MemoryStreamTest.txt", FileMode.Open, FileAccess.Read);  
        BinaryReader r = new BinaryReader (fs);  
  
        //以二进制方式读取文件中的内容  
        int i = r.ReadInt32 ();  
        float f = r.ReadSingle ();  
        double d = r.ReadDouble ();  
        bool b = r.ReadBoolean ();  
        string s = r.ReadString();  
        Debug.Log (i);  
        Debug.Log (f);  
        Debug.Log (d);  
        Debug.Log (b);  
        Debug.Log (s);  
  
        r.Close ();  
        fs.Close ();  
    }  
  
  	// 写入文件
    void WriteFile()       
    {  
        FileStream fs = new FileStream ("D:\\BinaryStreamTest.txt", FileMode.OpenOrCreate);  
        BinaryWriter w = new BinaryWriter (fs);  
  
        //以二进制方式向创建的文件中写入内容   
        w.Write (666);                   //  整型  
        w.Write (66.6f);                // 浮点型  
        w.Write (6.66);                // double型  
        w.Write(true);                 // 布尔型  
        w.Write ("六六六");         // 字符串型  
  
        w.Close ();  
        fs.Close();  
    }    
}  

StreamReader与StreamWriter

StreamReaderStreamWriter 通过使用特定编码在字符字节之间进行转换,提供了高效的流读写功能,可以直接用字符串进行读写,而不用转换成字节数组

文件编码
默认情况下,StreamReaderStreamWriter 类都使用 UTF-8编码。UTF-8编码正确处理 Unicode 字符并确保操作系统的本地化版本之间保持一致。

StreamWriter 类构造函数和常用方法如下:

函数描述
StreamWriter(Stream stream)构造函数,StreamWriter不仅能对FileStream对象,而且能够对NetWorkStream、MemoryStream等继承了Stream类的流对象进行封装;
StreamWriter(string path)构造函数,如需要处理的是文件流,则可直接利用文件路径创建以UTF8编码的StreamWriter对象;
StreamWriter(string path, Encoding encoding)构造函数,同上,可以指明编码格式
Write(string value)向数据流写入数据;
WriteLine(string value)向数据流写入数据,并追加一个换行符(Unix)或回车换行符(Windows);
Close()关闭流,释放资源;

StreamReader 类构造函数和常用方法如下:

函数描述
StreamReader(Stream stream)构造函数,利用流对象创建StreamReader对象;
StreamReader(string path)构造函数,如需要处理的是文件流,则可直接利用文件路径创建以UTF8编码的StreamReader对象;
StreamReader(string path, Encoding encoding)构造函数,同上,可以指明编码格式
string ReadLine()读取数据直到遇到换行符(Unix)或回车换行符(Windows);
string ReadToEnd()读取到文件尾的全部数据
int Peek()返回数据中下一个可用字符的编码值,如到达文件末尾则返回-1;
Close()关闭流,释放资源;
/// StreamReader读取文件
public string StreamReaderReadFile()
{
    string str="";
    try
    {
        FileStream file = new FileStream("love.txt", FileMode.Open);
        StreamReader sr = new StreamReader(file);
        while (sr.ReadLine()!=null)
        {
            str += sr.ReadLine();
        }
        //或者str = sr.ReadToEnd();
        sr.Close();
    }
    catch
    { }
    return str;
}

/// StreamWriter写文件
public void StreamWriterWriteFile()
{
     try
     {
         FileStream nFile = new FileStream("love.txt", FileMode.CreateNew);
         StreamWriter writer = new StreamWriter(nFile);
        
         writer.WriteLine("I love You!");
         writer.WriteLine("Do you love me!");
         writer.Close();
     }
     catch
     { }
} 
  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林新发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值