从文件读取和写入行

Reading and writing lines to and from a file

我正在使用 Microsoft Visual Basic 2010 Express 编写一个简单的控制台应用程序。我正在尝试制作一个 "newfile1.txt" 文件,其中将写一些标题,而不是说 10 行,每行三个单词。

之后,我想从文件中读取,并仅将文件 "newfile1.txt"

中的第二个单词写入 "newfile2" 文件

我想从这个文件中读取每一行,然后只存储 newfile1.txt

中的第二个单词

我尝试使用下面的代码,但我不知道如何指定一些东西(见下面的代码)

Module Module1

Sub Main()

    Dim i As Integer
    FileOpen(1, "C:\Users\Namba\Documents\ANALYZA MD\newFile1.txt", OpenMode.Append, OpenAccess.ReadWrite, OpenShare.Default)
    FileOpen(2, "C:\Users\Namba\Documents\ANALYZA MD\newFile2.txt", OpenMode.Append, OpenAccess.ReadWrite, OpenShare.Default)
    WriteLine(1, "Heading of the file1")

    For i = 1 To 10 Step 1
        WriteLine(1, "Word 1" & "Word 2" & "Word 3")
    Next
    FileClose(1)

    WriteLine(2, "Heading of the file2")
    Dim filereader As System.IO.StreamReader
    filereader = My.Computer.FileSystem.OpenTextFileReader("C:\Users\Namba\Documents\ANALYZA MD\newFile1.txt")
    Dim stringReader As String

    For i = 1 To 10 Step 1
        stringReader = filereader.ReadLine()
        WriteLine(2, stringReader)
    Next

End Sub 
End Module

所以我有几个问题:

  1. 是否可以通过 ReadLine 将单词存储到数组中或将每个单词存储到不同的字符串变量中?
  2. 是否有更简单的形式如何打开文件并读取每个单词,最终定义第一个单词将存储在字符串 var1 中,第二个单词存储在 var2 中等等,如果我们有一个文件,则类似带有数字,以便我想从此文件中读取并将每个数字存储到某个变量中。

我可以通过 READ() WRITE() 以非常简单的方式在 fortran 中轻松做到这一点

OPEN(UNIT=11, FILE="newfile1.txt)
READ(UNIT=11) x, y, z
OPEN(UNIT=12, FILE="newfile2.txt)
WRITE(UNIT=12,*) y

因此,这将从一个文件的第一行读取前 3 个单词(如果 x、y、z 声明为数字,则为数字),然后将第二个单词(或数字)写入第二个文件。

所以我想知道在 visual basic 中是否也有非常相似的东西?

一般来说,如果您的文件不大,那么将文件内容读入内存然后根据需要对其进行操作会更快(相对于代码编写而言)并且更容易。

希望这些示例会有所帮助。

' Read entire contents of file1.txt into an array.
Dim file1 As String() = System.IO.File.ReadAllLines("C:\file1.txt")

' Now extract the 2nd word from each line (assuming all lines have at least 2 words).
Dim secondWords As New List(Of String)
For Each line In file1
    ' Break apart the string by spaces and take the second index (word).
    secondWords.Add(line.Split(" ")(1))
Next

' Write the contents to a new file.
' This new file will have 1 word per line.
System.IO.File.WriteAllLines("C:\file2.txt", secondWords.ToArray())

如果你想检查每个单词,代码可以变成这样:

' Read entire contents of file1.txt into an array.
Dim file1 As String() = System.IO.File.ReadAllLines("C:\file1.txt")

' Process each line.
For Each line In file1
    ' Process each word within the line.
    For Each word In line.Split(" ")
        ' Do something with the word.
        Console.WriteLine(word)
    Next

    ' Or process by word index.
    Dim words As String() = line.Split(" ")
    For i As Integer = 0 To words.Length - 1
        Console.WriteLine(String.Format("Word {0} is {1}", i + 1, words(i)))
    Next

    Console.WriteLine("Moving to a new line.")
Next