Section 18.6. Reading Data from a Sequential-Access Text File


18.6. Reading Data from a Sequential-Access Text File

The preceding section demonstrated how to create a file for use in sequential-access applications. In this section, we discuss how to read (or retrieve) data sequentially from a file.

Class FrmReadSequentialAccessFile (Fig. 18.11) reads records from the file created in Fig. 18.9, then displays the contents of each record. Much of the code in this example is similar to that in Fig. 18.9, so we discuss only the unique aspects of the application.

Figure 18.11. Reading sequential-access files.

  1  ' Fig. 18.11: FrmReadSequentialAccessFile.vb  2  ' Reading a sequential-access file.  3  Imports System.IO  4  Imports BankLibrary ' imports classes from Figs. 18.7 and 18.8  5  6  Public Class FrmReadSequentialAccessFile  7     Private input As FileStream ' maintains connection to a file  8     Private fileReader As StreamReader ' reads data from a text file  9 10     ' invoked when user clicks the Open button 11     Private Sub btnOpen_Click(ByVal sender As System.Object, _ 12        ByVal e As System.EventArgs) Handles btnOpen.Click 13        ' create dialog box enabling user to open file 14        Dim fileChooser As New OpenFileDialog() 15        Dim result As DialogResult = fileChooser.ShowDialog() 16        Dim fileName As String ' name of file containing data 17 18        ' exit event handler if user clicked Cancel 19        If result = Windows.Forms.DialogResult.Cancel Then 20           Return 21        End If 22 23        fileName = fileChooser.FileName ' get specified file name 24        ClearTextBoxes() 25 26        ' show error if user specified invalid file 27        If fileName = "" Or fileName Is Nothing Then 28           MessageBox.Show("Invalid File Name", "Error", _ 29              MessageBoxButtons.OK, MessageBoxIcon.Error) 30        Else 31           ' create FileStream to obtain read access to file 32           input = New FileStream(fileName, FileMode.Open, FileAccess.Read) 33 34           ' set file from where data is read 35           fileReader = New StreamReader(input) 36 37           btnOpen.Enabled = False ' disable Open File button 38           btnNext.Enabled = True ' enable Next Record button 39        End If 40     End Sub ' btnOpen_Click 41 42     ' invoked when user clicks Next button 43     Private Sub btnNext_Click(ByVal sender As System.Object, _ 44        ByVal e As System.EventArgs) Handles btnNext.Click 45 46        Try 47           ' get next record available in file 48           Dim inputRecord As String = fileReader.ReadLine() 49 50           ' will store individual pieces of data 51           Dim inputFields() As String 52 53           If inputRecord IsNot Nothing Then 54              inputFields = inputRecord.Split(","c ) 55 56              Dim record As New Record(Convert.ToInt32( _ 57                 inputFields(0)), inputFields(1), inputFields(2), _ 58                 Convert.ToDecimal(inputFields(3))) 59 60             ' copy string array values to TextBox values 61             SetTextBoxValues(inputFields) 62          Else 63             fileReader.Close() ' close StreamReader 64             input.Close() ' close FileStream if no Records in file 65             btnOpen.Enabled = True ' enable Open File button 66             btnNext.Enabled = False ' disable Next Record button 67             ClearTextBoxes() 68 69             ' notify user if no Records in file 70              MessageBox.Show("No more records in file","", _ 71                 MessageBoxButtons.OK, MessageBoxIcon.Information) 72           End If 73        Catch ex As IOException 74           MessageBox.Show("Error Reading from File", "Error", _ 75              MessageBoxButtons.OK, MessageBoxIcon.Error ) 76        End Try 77     End Sub ' btnNext_Click 78  End Class ' FrmReadSequentialAccessFile 

(a)

(b)

(c)

(d)

(e)

(f)

(g)

(h)

When the user clicks the Open File button, the program calls event handler btnOpen_Click (lines 1140). Line 14 creates an OpenFileDialog, and line 15 calls its ShowDialog method to display the Open dialog (see the second screenshot in Fig. 18.11). The behavior and GUI for the Save and Open dialog types are identical, except that Save is replaced by Open. If the user inputs a valid file name, line 32 creates a FileStream object and assigns it to reference input. We pass constant FileMode.Open as the second argument to the FileStream constructor to indicate that the FileStream should open the file if it exists and throw a FileNotFoundException if the file does not exist. In the last example (Fig. 18.9), we wrote text to the file using a FileStream object with write-only access. In this example (Fig. 18.11), we specify read-only access to the file by passing constant FileAccess.Read as the third argument to the FileStream constructor (line 32). This FileStream object is used to create a StreamReader object in line 35. The FileStream object specifies the file from which the StreamReader object will read text.

Error-Prevention Tip 18.1

Open a file with the FileAccess.Read file-open mode if the contents of the file should not be modified. This prevents unintentional modification of the contents.


When the user clicks the Next Record button, the program calls event handler btnNext_Click (lines 4377), which reads the next record from the user-specified file. (The user must click Next Record after opening the file to view the first record.) Line 48 calls StreamReader method ReadLine to read the next record. If an error occurs while reading the file, an IOException is thrown (caught at line 73), and the user is notified (line 7475). Otherwise, line 53 determines whether StreamReader method ReadLine returned Nothing (i.e., there is no more text in the file). If not, line 54 uses method Split of class String to separate the stream of characters that was read from the file into strings that represent the Record's properties. Recall that the fields of each record are separated by commas. These properties are then stored by constructing a Record object using the properties as arguments (lines 5658). Line 61 displays the Record values in the TextBoxes by invoking method SetTextBoxes, which was inherited from class FrmBankUI. If ReadLine returns Nothing, the program closes both the StreamReader object (line 63) and the FileStream object (line 64), then notifies the user that there are no more records (lines 7071).



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net