日期:2009-05-30  浏览次数:20442 次

向字符串写入字符



下面的代码示例把从字符数组中指定位置开始的一定数目的字符写入现有的字符串。使用 StringWriter 完成此操作,如下所示。
 [C#]
using System;
using System.IO;
using System.Text;
 
public class CharsToStr
{
   public static void Main(String[] args)
   {
   // Create a StringBuilder object that can then be modified.
   StringBuilder sb = new StringBuilder("Some number of characters");
   // Define and initialize a character array from which characters
   // will be read into the StringBuilder object.
   char[] b = {' ','t','o',' ','w','r','i','t','e',' ','t','o','.'};
   // Create a StringWriter and attach it to the StringBuilder object.
   StringWriter sw = new StringWriter(sb);
   // Write three characters from the array into the StringBuilder object.
   sw.Write(b, 0, 3);
   // Display the output.
   Console.WriteLine(sb);
   // Close the StringWriter.
   sw.Close();
   }
}


此示例阐释了使用 StringBuilder 来修改现有的字符串。请注意,这需要一个附加的 using 声明,因为 StringBuilder 类是 System.Text 命名空间的成员。另外,这是一个直接创建字符数组并对其进行初始化的示例,而不是定义字符串然后将字符串转换为字符数组。

此代码产生以下输出:
Some number of characters to

构成流



后备存储器是一个存储媒介,例如磁盘或内存。每个不同的后备存储器都实现其自己的流作为 Stream 类的实现。每个流类型也都从其给定的后备存储器读取字节并向其给定的后备存储器写入字节。连接到后备存储器的流叫做基流。基流具有的构造函数具有将流连接到后备存储器所需的参数。例如,FileStream 具有指定路径参数(指定进程如何共享文件的参数)等的构造函数。

System.IO 类的设计提供简化的流构成。可以将基流附加到一个或多个提供所需功能的传递流。读取器或编写器可以附加到链的末端,这样便可以方便地读取或写入所需的类型。

下面的代码示例在现有 MyFile.txt 的周围创建 FileStream 对象,以缓冲 MyFile.txt。(请注意,默认情况下缓冲 FileStreams。)然后,创建 StreamReader 以读取 FileStream 中的字符,FileStream 被作为 StreamReader 的构造函数参数传递到 StreamReader。ReadLine 进行读取,直到 Peek 发现不再有字符为止。
 [C#]
using System;
using System.IO;
public class CompBuf {
   private const string FILE_NAME = "MyFile.txt";
   public static void Main(String[] args) {
      if (!File.Exists(FILE_NAME)) {
         Console.WriteLine("{0} does not exist!", FILE_NAME);
         return;
      }
      FileStream fsIn = new FileStream(FILE_NAME, FileMode.Open,
         FileAccess.Read, FileShare.Read);
      // Create a reader that can read characters from the FileStream.
      StreamReader sr = new StreamReader(fsIn); 
      // While not at the end of the file, read lines from the file.
      while (sr.Peek()>-1) {
         String input = sr.ReadLine();
         Console.WriteLine (input);
      }
      sr.Close();
   }
}


下面的代码示例在现有 MyFile.txt 的周围创建 FileStream 对象,以缓冲 MyFile.txt。(请注意,默认情况下缓冲 FileStreams。)然后,创建 BinaryReader 以读取 FileStream 中的字节,FileStream 被作为 BinaryReader 的构造函数参数传递到 Bi