文件读取

在stream中已经介绍过,文件读取应用filestream,其是以字节为单位读取文件的。在操作中,当应用filestream创建文件流,读取时应先定义一个字节数组,在转化成char类型,最后转化成string类型。我们其实可以通过streamreader/writer类来直接读取字符串。在此简单介绍一下,流的读取方式除了创建流类中自定义的read/write方法(通过byte类型进行),也可以通过其他读取类进行读取。streamreader/writer类,binaryread/write以及stringreader/writer均继承自textreader/writer抽象类,binaryreader/writer可以直接读取int,double,bool等数据类型,StreamReader/writer可直接读取字符串。

本例以filestream建立文件流,并通过StreamReader/writer进行读写。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FilestreamandStreamreader
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePathName = "E:\\test.txt";

            using (FileStream fs = new FileStream(filePathName, FileMode.Create, FileAccess.Write))
            {
                StreamWriter sw = new StreamWriter(fs);
                sw.Write("LIU");
                sw.WriteLine("Ljksdjfjk");
                sw.WriteLine("chengjisih");
                sw.Flush();
            }

            using (FileStream fs = new FileStream(filePathName, FileMode.Open, FileAccess.Read))
            {
                StreamReader sr = new StreamReader(fs);
                string str = sr.ReadToEnd();
                Console.WriteLine(str);
                fs.Position = 0;//每次重新调用时,fs位置归零
                Console.WriteLine(sr.ReadLine());

                //fs.Position = 0;
                //char[] chars = new char[10];
                //sr.Read(chars, 0, 10);
                //for (int i = 0; i < chars.Length; i++)
                //{
                //    Console.WriteLine(chars[i]);
                //}

                fs.Close();
                Console.ReadKey();
            }

        }
    }
}

streamreader其构造函数重载很多,可以满足不同的需求,只要是构造函数的入口参数为流都可以用它来读取,比如httpwebreponse等的返回值等,上例中
StreamReader sr = new StreamReader(fs)语句,入口参数可以直接为路径,也可以为
StreamReader sr = new StreamReader(File.Create(。。。。));继承自textreader/writer的三个派生类其实就是一个流的三种读取器,离开这三个类,用建立流对象的自身的write/read方法依旧可以。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值