chapter 9 files i/o: files, records and fields

21
Chapter 9 Files I/O: Files, Records and Fields Part 2

Upload: mayes

Post on 25-Feb-2016

38 views

Category:

Documents


2 download

DESCRIPTION

Chapter 9 Files I/O: Files, Records and Fields. Part 2. Sequential File Access - 1. Often talk in terms of ‘streams’ The stream of text to or from a data file - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 9 Files I/O:  Files, Records and Fields

Chapter 9Files I/O:

Files, Records and Fields

Part 2

Page 2: Chapter 9 Files I/O:  Files, Records and Fields

Sequential File Access - 1• Often talk in terms of ‘streams’• The stream of text to or from a data file• We control the stream of data coming in from a file or being written to

a file, but we do this with help from ‘objects’ that supply ‘methods’ to us to facilitate ‘reading’ and ‘writing’ data to a stream.

• Consider: Dim srdFile as System.IO.StreamReader• Declares / names an object called srdFile from StreamReader class.• srd stands for stream reader. (actually, not yet an object)

• Consider: srdFile = New System.IO.StreamReader (“GPA.dat”)• Actually creates the object and associates it with the file, GPA.dat.

• Also ‘opens the file.’• File prepared ahead of time should be in bin\Debug folder of your project.• Must be in this subdirectory or program will crash (according to book).

Page 3: Chapter 9 Files I/O:  Files, Records and Fields

Sequential File Access - 2• Much better ways to do this.• Immediate downside:• File name is hardcoded in program. So what??• No real flexibility here

• Consider: • Declare and create object at same time:• Dim srdFile as New System.IO.StreadReader (“GPA.dat”)

• Why create objects? What does this get us?• For classes that are defined in the language, you get the methods and

attributes!!

• Example: strLine = srdFile.ReadLine() ‘format: object.method• does what? Returns what?• Invokes ReadLine() method in the object srdFile, which reads the next line in the file, and

returns a string, which is assigned to strLIne for subsequent processing.

• Let’s put this stuff together…

Page 4: Chapter 9 Files I/O:  Files, Records and Fields

Sequential File Access – 3Code Example (book)

Private Sub btnRead_Click… Dim srdFile as System.IO.StreamReader ‘ what does this do? Dim strLine as String rtbOut.Clear() ‘ use lbx.Item.Add(…..) as you wish… rtbOut.AppendText (“ Student GPA” & ControlChars.NewLine &_ControlChars.NewLine) ‘ what does this do? Why?

srdFile = New System.IO.StreamReader (“GPA.dat”) ‘what does this do? Do until srdFile.Peek = -1 ‘ what is Peek?? method? strLine = srdFile.ReadLine()rtbOut.AppendText (strLine & vbNewLine) Loop srdFile.Close()End Sub

‘ no preprocessing shown; no real processing shown; no post processing shown. Think of any examples?

Page 5: Chapter 9 Files I/O:  Files, Records and Fields

More Significant Programming Example (book)

• A Sequential Files are organized in a number of different ways

• Fixed length fields (occupying specified position)

• Comma-delimited fields

• Space delimited fields

• Others (can specify)

Page 6: Chapter 9 Files I/O:  Files, Records and Fields

Input Master File DescriptionState Capital Abbrev Pop Region Region Nbr1-15 16-30 31-32 33-40 41-55 56 Washington Olympia WA 5689263West 6Oregon Salem OR 3281974West 6North_Carolina Raleigh NC 7546493South 3California Sacramento CA32182118West 6Idaho Boise ID 1228684West 6Montana Helena MT 880453West 6Wyoming Cheyenne WY 480907West 6Nevada Carson_City NV 1746898West 6Massachusetts Boston MA 6147132New_England 1Connecticut Hartford CT 3274069New_England 1Rhode_Island Providence RI 988480New_England 1New_York Albany NY18146200Middle_Atlantic2Pennsylvania Harrisburg PA12001451Middle_Atlantic2New_Jersey Trenton NJ 8115011Middle_Atlantic2Maryland Annapolis MD 5134808Middle_Atlantic2West_Virginia Charleston WV 1811156Middle_Atlantic2Virginia Richmond VA 6791345Middle_Atlantic2South_Carolina Columbia SC 3835962South 3

Fixed Length Records

Page 7: Chapter 9 Files I/O:  Files, Records and Fields

Comma Delimited Data File

Washington, Olympia, WA,5689263,West,6

Oregon,Salem,OR,3281974,West,6

North_Carolina,Raleigh,NC,7546493,South,3

Page 8: Chapter 9 Files I/O:  Files, Records and Fields

Space Delimited (White Space)

California Sacramento CA 32182118 West 6

Idaho Boise ID 1228684 West 6

Page 9: Chapter 9 Files I/O:  Files, Records and Fields

In VB, • Typically, we read in a record at a time via ReadLine() method.• Certainly other ways!

• Typically, record formats are fixed in • number of fields and • data types of fields (six fields: string, string, four ints)

• But if the records are not of type ‘fixed format,’ we often must ‘parse’ the record into its constituent fields.

• So, how to do this? Pretty easy.

• Need to parse based on a delimiter.

Page 10: Chapter 9 Files I/O:  Files, Records and Fields

More Significant Programming Example (book)

• Input the Data

• Dim strRecord() as String ‘ note: array of Strings.

• strLine = srdFinanceCharges.ReadLine • ‘srdFinanceCharges is object associated with the file name• ‘ reads a line from srdFinanceCharges object via ReadLine

• strRecord = strLine.Split(“,”) ‘ parse line using comma delimiter• strLast = strRecord(0)• strFirst = strRecord(1)• strAcctNo = strRecord(2)• decBalance = Convert.ToDecimal (strRecord(3))• tryParse(strRecord(3), decBalance)

• Given input record: Anderson, Andy, 39495, 2127.43• We’d get:• strRecord(0) = “Anderson”• strRecord(1) = “Andy”• strRecord (2) = “39495”• strRecord(3) = “2127.43”

Page 11: Chapter 9 Files I/O:  Files, Records and Fields

More Significant Programming Example (book)

• Note ALL are strings coming in from the input file. • The first three fields are strings and they remain as strings.• The code converts in the fourth case: decBalance = Convert.ToDecimal (strRecord(3))

(tryParse(strRecord(3), decBalance))

Process: We can now process as desired….Book reads each record and processes it, Multiplies decBalance by a percentage to determine finance charge. Accumulates total of the finance charges for all records.Produces a line of output in a rich Text Box. pretty standard stuff…

Page 12: Chapter 9 Files I/O:  Files, Records and Fields

More Significant Programming Example (book)

• More Processing of the detail records… • rtbOutput.Appendtext (strLast.PadRight(12) &_ strFirst.PadRight(12) & strAcctNo.PadRight(10) &_decBalance.ToString (“c”).PadLeft(11) &_ decFinanceCharge.ToString (“c”.PadLeft(10) & vbNewLine)

PadLeft() merely adds spaces to the left of the string (justifies right), while PadRight() adds spaces to the right of the string (justifies left).Note: we justify text on the left (PadRight()) andjustify numeric data on the right (PadLeft())

This also defines field size and brings about very nice alignment of columnar data.

See figure 9.3 in text.

Page 13: Chapter 9 Files I/O:  Files, Records and Fields

More Significant Programming Example (book)

• Postprocessing:• Close the file and produce any summary data.• This is usually totals, summary data, and things like that.

• From the program:• srdFinanceCharges.Close()

• rtbOut.AppendText (“Total Charges: “ &_ decTotal.ToString(“c”).PadLeft(41) & vbNewLine)

Page 14: Chapter 9 Files I/O:  Files, Records and Fields

File Output - 1• Can create a file offline using a word processor or a

spreadsheet or• Build the file from a program.

• Pretty straightforward.• Two methods available to objects in StreamWriter• CreateText (“file name”) and AppendText (“file name”)• CreateText(“filename”) creates a file; replaces existing file, so

be careful! Discuss.• AppendText (“filename”) creates a file, if it does not exist or

appends the records to the end of the file, if the named file does exist.

Page 15: Chapter 9 Files I/O:  Files, Records and Fields

File Output - 2• Consider the code:• Dim swrFile As System.IO.StreamWriter• swrFile = System.IO.File,CreateText(“filename.dat”)

• Or• swrFile = System.IO.File.AppendText(“filename.dat”)• swrFile.WriteLine(strDetail) ‘ assumes comma-delimited fields• swrFile.Close()

• Alternatively, if you want to build an output line one field at a time, you might write:

swrFile.Write(strDetail), which will write a field to a record.

To end the record, your last line ought to be a WriteLine() or a Write() followed by a vbNewLine to terminate the detail line.

Page 16: Chapter 9 Files I/O:  Files, Records and Fields

Dialog Boxes• Interested in Save File dialog box and Open File Dialog boxes.• Toolbox contains a whole set of these dialog boxes (bottom)• Add them to the component tray at the bottom of your forms.

• Allows us to specify an input file or output file name at run time! (like “testFile.dat”)

• Additional features: Can specify a directory and full path as well, such as C:\myDirectory\COP2010\wgabra.txt

• Consider:

Page 17: Chapter 9 Files I/O:  Files, Records and Fields

Open File Dialog Boxes• OpenFileDialog Control• Once an OpenFileDialog box is in your component tray, we can activate the code: <will show on next slides> and

allow a user to browse through drives and folders to determine the file to be opened.

• Selected filename from the dialog box is copied into the FileName property of the OpenFileDialog control (whatever you have named it) and we can then have the srdFile object pointing to the desired Filename to read the data..

Page 18: Chapter 9 Files I/O:  Files, Records and Fields

Open File Dialog BoxesHow to get there…Project 3

1. Create test file, call it TestVB using Notepad and save it all the way down in your projects folder,…\ bin\Debug.Be sure to put some names in it to simulate Justin’s sample file.

2. Add all the Menu strips to your form that are required for project 3. (We can activate later)For File you will have Open… Save As… Clear, and Exit. (We need the Open… to get started)

3. Go to the Dialog section in your Toolbox and select OPenFileDialog.Double click on the OpenFileDialog controlAn OpenFileDialogBox will appear in your component trayGo to the Name attribute and change name to OpenFD (nothing sacred about this name)

4. Go to your menu: File…Open… and click. This will take you to the code windowGo to the code window and see the Sub code provided: You get: Private Sub ToolStripMenuItem1_Click …. Handles ToolStripMenuItem1.Click5. Add the code: OpenFD.ShowDialog() ‘When you execute, this will bring up a dialog box for this project and will display the contents of the …\bin\Debug subdirectory. .

Page 19: Chapter 9 Files I/O:  Files, Records and Fields

Open File Dialog BoxesHow to get there…Project 3

6. When you execute your program, Select your text file from that subdirectory and Press OK.

7. Note: You have not read or processed anything in the file…

------------------------------------------------------------------------------------------An Aside: you can do more:You can cite initial directory and tag the Dialog Box; Default seems to be \bin\Debug

OpenFD.InitialDirectory = _ "C:\Users\Bob\My Documents\Visual Studio 2010\Projects\SomeOtherPlaceOpenFD.Title = "Open a Text File“ ‘titles the Dialog BoxOpenFD.ShowDialog() ‘ displays the dialog box

You can also Filter the types of files displayed in this directory to *.txt or *.doc….if you wish. Especially convenient if the subdirectory contains a large number of files of different types.

Page 20: Chapter 9 Files I/O:  Files, Records and Fields

Open File Dialog Boxes: more So now that you have opened the file, we need to read it.Recommend doing a very little at a time and verifying!!!!Here’s my code to date:Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click Dim str As String Dim srdFile As System.IO.StreamReader ‘ declares a potential object of StreamReader OpenFD.InitialDirectory = "C:\Users\Bob\My Documents\Visual _

Studio2010\Projects\ParallelArrays\ParallelArrays\bin\Debug" OpenFD.Title = "Open a Text File“ ‘ Titles the Dialog Box OpenFD.ShowDialog() ‘ Displays the Dialog Box for that directory

‘ Select your text file.‘ ShowDialog() returns FileName you selected

srdFile = New System.IO.StreamReader(OpenFD.FileName) ‘ Creates srdFile object that points to the file; and Opens it.

Do Until srdFile.Peek = -1 ' Peek = -1 implies EOF str = srdFile.ReadLine() ‘ Reads a line from the file. If str <> "" Then ' skips a null line as specified lbxNames.Items.Add(str + vbNewLine) ‘ For me: printed out line of the file. No parsing parseLine(str) ' Call parseLine to identify the tokens in the line. End If Loop srdFile.Close() ‘ Close file when done lbxNames.Items.Add("File Closed") ‘ Probe for me. End Sub

Page 21: Chapter 9 Files I/O:  Files, Records and Fields

Open File Dialog Boxes: more