如何掌握強(qiáng)大的VB.NET ReadLine()方法
經(jīng)過長時間學(xué)習(xí)VB.NET ReadLine()方法,于是和大家分享一下,看完本文你肯定有不少收獲,希望本文能教會你更多東西。
現(xiàn)在,讓我們來實現(xiàn)讀取輸入文件和寫入輸出文件。我們將每一行讀取到一個字符串?dāng)?shù)組中,然后輸出該字符串?dāng)?shù)組。在下一步中,我們將使用 QuickSort 算法來對該數(shù)組進(jìn)行排序。
修改源代碼
更改 C# 源文件 (class1.cs),如下面以斜體突出顯示的代碼所示。其他的差異(如類名)可忽略不計。
- // Import namespaces
- using System;
- using System.Collections;
- using System.IO;
- // Declare namespace
- namespace MsdnAA
- {
- // Declare application class
- class QuickSortApp
- {
- // Application initialization
- static void Main (string[] szArgs)
- {
- ... ... ...
- // Read contents of source file
- string szSrcLine;
- ArrayList szContents = new ArrayList ();
- FileStream fsInput = new FileStream (szSrcFile, FileMode.Open,
- FileAccess.Read);
- StreamReader srInput = new StreamReader (fsInput);
- while ((szSrcLine = srInput.ReadLine ()) != null)
- {
- // Append to array
- szContents.Add (szSrcLine);
- }
- srInput.Close ();
- fsInput.Close ();
- // TODO: Pass to QuickSort function
- // Write sorted lines
- FileStream fsOutput = new FileStream (szDestFile,
- FileMode.Create, FileAccess.Write);
- StreamWriter srOutput = new StreamWriter (fsOutput);
- for (int nIndex = 0; nIndex < szContents.Count; nIndex++)
- {
- // Write line to output file
- srOutput.WriteLine (szContents[nIndex]);
- }
- srOutput.Close ();
- fsOutput.Close ();
- // Report program success
- Console.WriteLine ("\nThe sorted lines have been written.\n\n");
- }
- }
- }
從源文件進(jìn)行讀取
使用 FileStream 類打開源文件,然后加入 StreamReader 類,這樣我們就可以使用它的VB.NET ReadLine()方法了?,F(xiàn)在,我們調(diào)用VB.NET ReadLine()方法,直到它返回 null,這表示到達(dá)文件結(jié)尾。在循環(huán)過程中,我們將讀取的行存儲到字符串?dāng)?shù)組中,然后關(guān)閉這兩個對象。
寫入輸出文件
假設(shè)已經(jīng)用 QuickSort 對字符串?dāng)?shù)組進(jìn)行了排序,接下來要做的事情就是輸出數(shù)組的內(nèi)容。按照同樣的方式,我們將 StreamWriter 對象附加到 FileStream 對象上。這使得我們可以使用 WriteLine() 方法,該方法能夠很方便地模仿 Console 類的行為。一旦遍歷了數(shù)組,我們便可以象前面一樣關(guān)閉這兩個對象。
【編輯推薦】