|
|
|
|
步骤 6. 文件输入/输出 现在,让我们来实现读取输入文件和写入输出文件。我们将每一行读取到一个字符串数组中,然后输出该字符串数组。在下一步中,我们将使用 QuickSort 算法来对该数组进行排序。 修改源代码更改 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"); } } } 从源文件进行读取使用 FileStream 类打开源文件,然后加入 StreamReader 类,这样我们就可以使用它的 ReadLine() 方法了。现在,我们调用 ReadLine() 方法,直到它返回 null,这表示到达文件结尾。在循环过程中,我们将读取的行存储到字符串数组中,然后关闭这两个对象。
写入输出文件假设已经用 QuickSort 对字符串数组进行了排序,接下来要做的事情就是输出数组的内容。按照同样的方式,我们将 StreamWriter 对象附加到 FileStream 对象上。这使得我们可以使用 WriteLine() 方法,该方法能够很方便地模仿 Console 类的行为。一旦遍历了数组,我们便可以象前面一样关闭这两个对象。
|



