zoukankan      html  css  js  c++  java
  • StreamWriter类的一般使用方法

        理解StreamWriter可以对照StreamReader类来进行,因为他们只是读写的方式不同,一个是读,一个是写,其他的差别不是特别大。

        StreamWriter继承于抽象类TextWriter,是用来进行文本文件字符流写的类。

        它是按照一种特定的编码从字节流中写入字符,其常用的构造函数如下:

    public StreamWriter (string path)//1
    public StreamWriter (string path,bool append)//2
    public StreamWriter (string path,bool append,Encoding encoding)//3

    第1个构造函数,是以默认的形式进行,字符的编码依旧是UTF-8.

    第2个构造函数,是1的具体话,引入了一个参数append,这个参数决定了当文件存在的时候,是覆盖还是追加,如果为false,则是覆盖,如果为true,则是追加,1的本质是public StreamWriter (string path,false)

    第三个构造函数是2的具体化,引入了具体的字符编码Encoding,默认的情况是UTF-8。

    如果文件不存在,会自动创建文件。

     StreamWriter的两个重要的方法是Write()与WriteLine()。下面具体来说一说。

    Write(string)方法是直接将string写入到文件中,而WriteLine(string)写完string加了一个回车换行,参见下面的代码的区别:

    Write
    using System;
    using System.IO;
    using System.Text;

    class Test
    {

    public static void Main()
    {
    try
    {
    using (StreamWriter sw= new StreamWriter("TestFile.txt"))
    {
    string str1 = "abc";
    string str2 = "def";
    sw.Write(str1);
    sw.Write(str2);
    }
    }
    catch (Exception e)
    {
    Console.WriteLine(
    "The file could not be read:");
    Console.WriteLine(e.Message);
    }
    }
    }
    WriteLine
    using System;
    using System.IO;
    using System.Text;

    class Test
    {

    public static void Main()
    {
    try
    {
    using (StreamWriter sw= new StreamWriter("TestFile.txt"))
    {
    string str1 = "abc";
    string str2 = "def";
    sw.WriteLine(str1);
    sw.WriteLine(str2);
    }
    }
    catch (Exception e)
    {
    Console.WriteLine(
    "The file could not be read:");
    Console.WriteLine(e.Message);
    }
    }
    }

    打开文件TestFile.txt就能找到它们的区别了。

  • 相关阅读:
    Jenkins中构建Testcomplete项目的方法介绍
    抖音批量,批量运营抖音_不要迷恋我_【单月抖音变现7000万】教程
    java 读取 excel 表格内容
    .NET Core 2.1中的分层编译(预览)
    Windows10上使用Linux子系统(WSL)
    swagger上传文件并支持jwt认证
    .NET微服务 容器化.NET应用架构指南(支持.NET Core2)
    用C#编写Linux守护进程
    安装mysql后运行.net程序出错
    2018 你好
  • 原文地址:https://www.cnblogs.com/wxhpy7722/p/2149886.html
Copyright © 2011-2022 走看看