❮ 上一节

下一节 ❯

VB.Net - 读取和写入文本文件

StreamReader 和 StreamWriter 类用于从文本文件读取数据或向文本文件写入数据。 这些类继承自抽象基类 Stream,它支持在文件流中读取和写入字节。

StreamReader 类

StreamReader 类还继承自抽象基类 TextReader,它表示用于读取一系列字符的阅读器。 下表描述了StreamReader类的一些常用方法 −

序号

方法名称 & 用途

1

Public Overrides Sub Close

它关闭 StreamReader 对象和底层流,并释放与读取器关联的所有系统资源。

2

Public Overrides Function Peek As Integer

返回下一个可用字符,但不使用它。

3

Public Overrides Function Read As Integer

从输入流读取下一个字符,并将字符位置前进一个字符。

示例

以下示例演示读取名为 Jamaica.txt 的文本文件。 文件读取 −

Down the way where the nights are gay

And the sun shines daily on the mountain top

I took a trip on a sailing ship

And when I reached Jamaica

I made a stop

Imports System.IO

Module fileProg

Sub Main()

Try

' 创建 StreamReader 的实例以从文件中读取。

' using 语句还会关闭 StreamReader。

Using sr As StreamReader = New StreamReader("e:/jamaica.txt")

Dim line As String

' 读取并显示文件中的行,直到到达文件末尾。

line = sr.ReadLine()

While (line <> Nothing)

Console.WriteLine(line)

line = sr.ReadLine()

End While

End Using

Catch e As Exception

' 让用户知道哪里出错了。

Console.WriteLine("The file could not be read:")

Console.WriteLine(e.Message)

End Try

Console.ReadKey()

End Sub

End Module

猜猜当你编译并运行程序时它会显示什么!

StreamWriter 类

StreamWriter类继承自代表一个写入器的抽象类TextWriter,它可以写入一系列字符。

下表显示了该类的一些最常用的方法 −

序号

方法名称 & 用途

1

Public Overrides Sub Close

关闭当前的 StreamWriter 对象和底层流。

2

Public Overrides Sub Flush

清除当前写入器的所有缓冲区,并使所有缓冲数据写入底层流。

3

Public Overridable Sub Write (value As Boolean)

将布尔值的文本表示形式写入文本字符串或流。 (继承自TextWriter。)

4

Public Overrides Sub Write (value As Char)

将一个字符写入流。

5

Public Overridable Sub Write (value As Decimal)

将十进制值的文本表示形式写入文本字符串或流。

6

Public Overridable Sub Write (value As Double)

将 8 字节浮点值的文本表示形式写入文本字符串或流。

7

Public Overridable Sub Write (value As Integer)

将 4 字节有符号整数的文本表示形式写入文本字符串或流。

8

Public Overrides Sub Write (value As String)

将字符串写入流。

9

Public Overridable Sub WriteLine

将行终止符写入文本字符串或流。

上面的列表并不详尽。 有关方法的完整列表,请访问 Microsoft 的文档

示例

以下示例演示使用 StreamWriter 类将文本数据写入文件 −

Imports System.IO

Module fileProg

Sub Main()

Dim names As String() = New String() {"Zara Ali", _

"Nuha Ali", "Amir Sohel", "M Amlan"}

Dim s As String

Using sw As StreamWriter = New StreamWriter("names.txt")

For Each s In names

sw.WriteLine(s)

Next s

End Using

' 读取并显示文件中的每一行。

Dim line As String

Using sr As StreamReader = New StreamReader("names.txt")

line = sr.ReadLine()

While (line <> Nothing)

Console.WriteLine(line)

line = sr.ReadLine()

End While

End Using

Console.ReadKey()

End Sub

End Module

当上面的代码被编译并执行时,会产生以下结果 −

Zara Ali

Nuha Ali

Amir Sohel

M Amlan

❮ vb.net_file_handling.html

❮ 上一节

下一节 ❯