| 网站首页 | 业界新闻 | 技术文章 | 视频教程 | 下载频道 | 程序源码 | 个人空间 | 编程论坛 |
 
 
 
您现在的位置: 编程中国 >> 技术教程 >> .NET技术 >> VB.NET >> VB.NET教程 >> 正文
  ►  VB.NET 入门教程
VB.NET 入门教程
作者:未知    阅读人次:……    文章来源:microsoft    发布时间:2004-9-27    网友评论()条
 

 

步骤 6. 文件输入/输出

现在,让我们来实现读取输入文件和写入输出文件。我们将每一行读取到一个字符串数组中,然后输出该字符串数组。在下一步中,我们将使用 QuickSort 算法来对该数组进行排序。

修改源代码

更改 Visual Basic 源文件 (module1.vb),如下面以斜体突出显示的代码所示。其他的差异(如类名)可忽略不计。

' Import namespaces
Imports System
Imports System.Collections
Imports System.IO
Module Module1
    Sub Main()
        ... ... ...
        ' Read contents of source file
        Dim szSrcLine As String
        Dim szContents As ArrayList
        Dim fsInput As FileStream
        Dim srInput As StreamReader
        szContents = New ArrayList()
        fsInput = New FileStream(szSrcFile, FileMode.Open, FileAccess.Read)
        srInput = New StreamReader(fsInput)
        szSrcLine = srInput.ReadLine()
        While Not IsNothing(szSrcLine)
            ' Append to array
            szContents.Add(szSrcLine)
            szSrcLine = srInput.ReadLine()
        End While
        srInput.Close()
        fsInput.Close()
        ' TODO: Pass to QuickSort function
        ' Write sorted lines
        Dim fsOutput As FileStream
        Dim srOutput As StreamWriter
        Dim nIndex As Integer
        fsOutput = New FileStream(szDestFile, FileMode.Create, _
            FileAccess.Write)
        srOutput = New StreamWriter(fsOutput)
        For nIndex = 0 To szContents.Count – 1
            ' Write line to output file
            srOutput.WriteLine(szContents(nIndex))
        Next nIndex
        srOutput.Close()
        fsOutput.Close()
        ' Report program success
        Console.WriteLine()
        Console.WriteLine("The sorted lines have been written.")
        Console.WriteLine()
    End Sub
End Module 

从源文件进行读取

使用 FileStream 类打开源文件,然后加入 StreamReader 类,这样我们就可以使用它的 ReadLine() 方法了。现在,我们调用 ReadLine() 方法,直到它返回 null,这表示到达文件结尾。在循环过程中,我们将读取的行存储到字符串数组中,然后关闭这两个对象。

 

a

 

写入输出文件

假设已经用 QuickSort 对字符串数组进行了排序,接下来要做的事情就是输出数组的内容。按照同样的方式,我们将 StreamWriter 对象附加到 FileStream 对象上。这使得我们可以使用 WriteLine() 方法,该方法能够很方便地模仿 Console 类的行为。一旦遍历了数组,我们便可以像前面一样关闭这两个对象。

 


 

上一页  [1] [2] [3] [4] [5] [6] [7] [8] 下一页

 

 
文章录入:静夜思    责任编辑:静夜思 
  • 上一篇文章: 没有了

  • 下一篇文章:

  •  
    相关文章
    没有相关文章
    原创地带
    24小时热门帖子