Example 042 reading and writing text files

TextReader class

https://docs.microsoft.com/zh-cn/dotnet/api/system.io.textreader?view=netframework-4.8

Namespace: System.IO

Assembly: mscorlib.dll

Represents a reader that can read ordered character series.

The TextReader  class is an abstract class. So don't instantiate it in code. The StreamReader  class is derived from  TextReader and provides member implementations to read from the stream.

      The TextReader class is used to read text files, and the StreamReader class is inherited by the TextReader class. The methods of the StreamReader class mainly include:

  • Read reads the next character from the file stream;
  • ReadLine reads a line of characters from the file stream;
  • ReadToEnd reads from the current position of the file stream to the end of the stream;
  • Peek, returns the next character in the file stream, but does not read this character.

       There are two ways to create a StreamReader object, one is to create a file path name, and the other is to create a TextReader class from an already created file stream object.
    The TextWriter class is used to rewrite the content of a text file, and the StreamWriter class is inherited by the TextWriter class.

The methods of the StreamWriter class include:

  • Write write data to a text file;
  • WriteLine write a line;
  • Close, close the file stream and release resources.

    The StreamWriter class can also construct objects in two ways, one is created by the file path name, and the other is created by the already created file stream object.

Module Module1

    Sub Main()
        testTextFile()

        Console.Read()
    End Sub

    Private Sub testTextFile()
        Dim TextLine As String = ""
        Dim Fs As IO.FileStream
        Dim Sw As IO.StreamWriter
        Dim Sr As IO.StreamReader

        Fs = New IO.FileStream("j:\test\TextReader.txt", IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
        Sw = New IO.StreamWriter(Fs)
        Dim flag As Boolean = True
        While flag
            Console.WriteLine("输入一行字,回车键退出。")
            TextLine = Console.ReadLine()
            If TextLine = "" Then
                flag = False
            Else
                Sw.WriteLine(TextLine)
            End If
        End While
        Sw.Close()

        Fs = New IO.FileStream("j:\test\TextReader.txt", IO.FileMode.Open, IO.FileAccess.Read)
        Sr = New IO.StreamReader(Fs)
        flag = True
        While flag
            If Sr.Peek = -1 Then
                flag = False
            Else
                TextLine = Sr.ReadLine
                Console.WriteLine(TextLine)
            End If
        End While
        Sr.Close()

    End Sub
End Module
 

Published 146 original articles · won praise 0 · Views 2726

Guess you like

Origin blog.csdn.net/ngbshzhn/article/details/105616549