File I/O Part 2

advertisement
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
• 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).
Sequential File Access - 2
• Much better ways to do this.
• Immediate downside:
• File name is hardcoded in program.
• No real flexibility here
So what??
• 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…
Sequential File Access – 3
Code 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?
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)
Fixed Length Records
Input Master File Description
State
Capital Abbrev Pop Region Region Nbr
1-15
16-30 31-32 33-40 41-55
56
Washington
Oregon
North_Carolina
California
Idaho
Montana
Wyoming
Nevada
Massachusetts
Connecticut
Rhode_Island
New_York
Pennsylvania
New_Jersey
Maryland
West_Virginia
Virginia
South_Carolina
Olympia
Salem
Raleigh
Sacramento
Boise
Helena
Cheyenne
Carson_City
Boston
Hartford
Providence
Albany
Harrisburg
Trenton
Annapolis
Charleston
Richmond
Columbia
WA 5689263West
6
OR 3281974West
6
NC 7546493South
3
CA32182118West
6
ID 1228684West
6
MT 880453West
6
WY 480907West
6
NV 1746898West
6
MA 6147132New_England
1
CT 3274069New_England
1
RI 988480New_England
1
NY18146200Middle_Atlantic2
PA12001451Middle_Atlantic2
NJ 8115011Middle_Atlantic2
MD 5134808Middle_Atlantic2
WV 1811156Middle_Atlantic2
VA 6791345Middle_Atlantic2
SC 3835962South
3
Comma Delimited Data File
Washington, Olympia, WA,5689263,West,6
Oregon,Salem,OR,3281974,West,6
North_Carolina,Raleigh,NC,7546493,South,3
Space Delimited (White Space)
California
Idaho
Sacramento
Boise
CA 32182118 West
ID 1228684 West
6
6
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.
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”
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…
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()) and
justify 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.
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)
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.
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.
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:
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..
Open File Dialog Boxes
How 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 control
An OpenFileDialogBox will appear in your component tray
Go 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 window
Go to the code window and see the Sub code provided: You get:
Private Sub ToolStripMenuItem1_Click ….
Handles ToolStripMenuItem1.Click
5. 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. .
Open File Dialog Boxes
How 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\SomeOtherPlace
OpenFD.Title = "Open a Text File“
‘titles the Dialog Box
OpenFD.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.
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
Open File Dialog Boxes: more
Download