我正在使用Microsoft Visual Basic 2010 express编写一个简单的控制台应用程序。我正在尝试创建一个“newfile1.txt”文件,其中将写入一些标题,而不是说每行有三个单词的10行。
之后,我想从文件中读取,并将“newfile2”文件只写入文件“newfile1.txt”中的第二个单词
我想从每个行读取此文件,而store只允许存储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
所以我有几个问题:
我可以通过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中是否也有类似的东西?
答案 0 :(得分:0)
一般来说,如果你的文件不是很大,那么它就会更快(关于代码编写),并且更容易将文件内容读入内存,然后根据需要进行操作。
希望这些例子会有所帮助。
' 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