zoukankan      html  css  js  c++  java
  • 基本文件的I/O

    System.IO命名空间包含允许在数据流和文件上进行同步,异步及写入的类型。文件是一些永久存储及具有特定顺序的字节组成的一个有序的,具有名称的集合。与文件有关的概念是目录路径和磁盘存储等。流提供了一种向后备存储写入字节和从后备存储读取字节的方式。后备存储包裹用文件存储或用内存(数组)存储,以及网络,CD等。

    基本文件的I/O

      命名空间为System.I/O,程序集为mscorlib(在mscorlib.dll中)

      抽象基类Stream支持读取和写入字节。Stream集成了异步支持,其默认实现根据其相应的异步方法来定义同步读取和写入。

      所有表示流的类都是从Stream类继承的。Stream类及其派生类提供数据源和存储库的一般视图,使程序员不必了解操作系统和基础设备的具体细节。

      流涉及3个基本操作:从流读取,向流写入以及查找和修改流内当前位置。根据基础数据源或存储库,流可能只支持这些功能中的一部分。例如,NetworkStream不支持查找。Stream的CanRead,CanWrite和CanSeek属性及其派生类决定不同的流所支持的操作。

    Stream类

      stream是所有流的抽象基类。流是字节序列的抽象概念,如文件,输入输出设备,内部进程通信管道或TCP/IP套接字。Stream类及其派生类提供这些不同类型的输入输出的一般视图,使程序员不必了解操作系统和基础设备的具体细节。

      如果用MemoryStream初始化流,流的后备存储是内存,容量随数据动态的增加。如果用FileStream初始化流,流的后备存储是文件,对流的操作视同对文件的操作。

      下面的例子使用Stream..WriteByte和Stream..Read写入和读取数据块

    using System;

    using System.IO;

    public class Block

    {

      public static void main()

      {

        Stream s=new MemoryStream();//产生一个流,它的后备存储是内存

        //将一个字节写入流内的当前位置,位置推进一个字节

        for(int i=0;i<100;i++)

        {

          s.WtriteByte((byte)i);

        }

        s.Positon=0;//流中位置设置为0

        byte[]betes=new byte[1000];

        //请求从流中读取的最大字节数等于流的长度

        int numBytesToRead=(int)s.Length;

        int numBytesRead=0;//偏移量设置为0

        while(numBytesToRead>0)

        {

          //s.Read从当前流读取字节序列,并将此流中的位置提升读取的字节数

          //返回值n是实际读取的字节数,如果已到达流的末尾则为零(0)

          int n=s.Read(   bytes,       //数组bytes接收从流中读取的字节

                  numBytesRead,   //数组bytes的偏移量,从偏移量开始存储数据

                  numBytesToRead);//请求读取的最大字节数

          if(n==0)

          {

            break;

          }

          numBytesRead+=n;

          numBytesToRead-=n;

        }

        s.Close();

        //现在请求读取的字节数numBytesToRead为0,偏移量numBytesRead应该为100

        Console.WriteLine("number of bytes read:"+numBytesRead);

      }

    }

    输出如下:

    number of bytes read:100

    File类
      file类提供用于创建,复制,删除,移动和打开文件的静态方法,并协助创建FileStream对象。也可将File类用于获取和设置文件属性或有关文件创建,访问及写入操作的DateTime信息。由于所有的File方法都是静态的,因此如果只想执行一个操作,则使用File方法的效果比使用相应的FileInfo实例方法可能更高

      下面演示File类的一些主要成员。代码中使用Using语句定义一个范围。将下面的代码放入Main方法。

    string path=@".....MyTest.txt";//MyTest.txt位于项目的文件夹

    if(!File.Exits(path))

    {

      //using语句用于定义一个范围,再次范围的末尾将释放对象sw

      //StreamWriter实现一个TextWriter,使其以特定的编码UTF-8向流中写入字符

      //File.CreateText创建或打开一个文件用于写入UTF-8编码的文本

      using(StreamWriter sw=FIle.CreateText(path))

      {

        sw.WriteLine("Hello");

        sw.WriteLine("AND");

        sw.WriteLine("Welcome");

      }

    }

    //使用StreamReader读取标准文本文件的各行信息

    using (StreamReader sr=File.OpenText(path))

    {

      string s="";

      //从当前的流中读出一行字符将数据作为字符串返回

      while((s=sr.ReadLine())!=null)

      {

        //显示Mytext.txt的内容“Hello/And/Welcome”到屏幕

        Console.WriteLine(s);

      }

    }

    try

    {

      string path2=path+"temp";

      File.Delete(path2);//确保目标文件不存在

      File.Copy(path,path2);//复制文件

      Console.WriteLine("{0}was copied to {1}",path,path2);

      File.Delete(path2);

      Console.WriteLine("{0}was successfully deleted.",path2);

    }

    catch(Exception e)

    {

      Console.WriteLine("The process failed:{0}",e.ToString());

    }

    运行结果为程序在本项目文件夹建立一个文本文件MyText.txt,屏幕显示为:

    Hello/And/Welcome

    ....myTest.txt was copied to....myTest.txttemp

    ....myTest.txt was successfully deleted

    FileInfo类

      FileInfo类提供创建,复制,删除,移动和打开文件的实例方法,并且帮助创建FileStream对象,如果打算多次重用某个对象,可考虑使用FileInfo的实例方法,而不是File类的相对静态方法,以内并不总是需要安全检查

      下面的例子是使用FileInfo构造函数创建两个文件,并接着对其进行写入,读取,复制和删除操作

    string path=@"....MyText.txt"

    FileInfo fil=new FileInfo(path);    //FileInfo提供的方法是非静态方法,必须实例化

    if(!fil.Exists)

    {

      using(StreamWriter sw=fil.CreaterText())

      {

        sw.WriteLine("Hello");

        sw.WriteLine("And");

        sw.WriteLine("Welcome");  

      }

    }

    using(StreamReader sr=fil.OpenText())

    {

      string s="";

      while((s=sr.ReadLine())!=null)  

        Console.WriteLine(s);

    }

    try

    {

      string path2=path+"temp";

      FileInfo fi2=new FileInfo(path2);

      fi2.Delete();    //确保目标文件不存在

      fi1.CopyTo(path2);  //复制文件

      Console.WriteLine("{0}was copied to {1}",path,path2);

      fi2.Delete();

      Console.WriteLine("{0}was successfully deleted",path2);

    }

    catch(Exception e)

    {

      Console.WriteLine("The process failed:{0}",e.Tostring());

    }

    运行结果为

    Hello/And/Welcome

    ....myTest.txt was copied to....myTest.txttemp

    ....myTest.txt was successfully deleted

    下面的一个例子是显示FileInfo的一些主要成员

    //创建磁盘上给你唯一命名的零字节的临时文件并返回该文件的完整路径

    //此方法创建带.TMP文件拓展名的临时文件

    string path=Path.GetTempFileName();

    //初始化FileInfo类的新实例,它作为文件路径的包装

    FileInfo fil=new FileInfo(path);

    if(!fil.Exists)

    {

      //fil.CreateText创建吸入新文本文件的StreamWriter

      //默认情况下,将向所有用户授予对于新文件的完全读写访问权限

      using(StreamWriter sw=fil.CreateText())

      {

        sw.WriteLine("Hello");

        sw.WriteLine("And");

        sw.WriteLine("Welcome");

      }

    }

    using(StreamReader sr=fil.OpenText())//打开文件读取

    {

      string s="";

      while((s=sr.ReadLine())!=null)

        Console.WriteLine(s);

    }

    try

    {

      string path2=Path.GetTempFileName();

      FileInfo fi2=new FileInfo(path2);

      fi2.Delete();

      fi1.CopyTo(path2);

      Console.WriteLine("{0}was copied to{1}",path,path2);

      fi2.Delete();

      Console.WriteLine("{0}was successfully deleted.",path2)  

    }

    catch(Exception e)

    {

      Console.WriteLine("The process failed:{0}",e.ToString());

    }

    运行结果如下:

    C:Documents and SettingsAdministratorLocal Settings empTemp10.tmp was copied to

    C:Documents and SettingsAdministratorLocal Settings empTemp11.tmp

    C:Documents and SettingsAdministratorLocal Settings empTemp11.tmp was successfully deleted

  • 相关阅读:
    [POJ 1417] True Liars
    [POJ 2912] Rochambeau
    [NOIP 2010] 关押罪犯
    [BZOJ 3365] Distance Statistics
    【BZOJ 2821】作诗
    【IOI 2011】Race
    【POJ 2828】Buy Tickets
    FATFS 文件系统
    w25q128 优化读写函数
    keil5编译时出现 MDK-Pro middleware is not allowed with this license
  • 原文地址:https://www.cnblogs.com/yk1992/p/3588404.html
Copyright © 2011-2022 走看看