1 / 21

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

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

Download Presentation

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

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  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).

  3. 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 createobject 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 strLInefor subsequent processing. • Let’s put this stuff together…

  4. 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?

  5. 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)

  6. Fixed Length Records Input Master File Description State Capital Abbrev Pop Region RegionNbr 1-15 16-30 31-32 33-40 41-55 56 Washington Olympia WA 5689263West 6 Oregon Salem OR 3281974West 6 North_Carolina Raleigh NC 7546493South 3 California Sacramento CA32182118West 6 Idaho Boise ID 1228684West 6 Montana Helena MT 880453West 6 Wyoming Cheyenne WY 480907West 6 Nevada Carson_CityNV 1746898West 6 Massachusetts Boston MA 6147132New_England 1 Connecticut Hartford CT 3274069New_England 1 Rhode_Island Providence RI 988480New_England 1 New_York Albany NY18146200Middle_Atlantic2 Pennsylvania Harrisburg PA12001451Middle_Atlantic2 New_Jersey Trenton NJ 8115011Middle_Atlantic2 Maryland Annapolis MD 5134808Middle_Atlantic2 West_Virginia Charleston WV 1811156Middle_Atlantic2 Virginia Richmond VA 6791345Middle_Atlantic2 South_Carolina Columbia SC 3835962South 3

  7. Comma Delimited Data File Washington, Olympia, WA,5689263,West,6 Oregon,Salem,OR,3281974,West,6 North_Carolina,Raleigh,NC,7546493,South,3

  8. Space Delimited (White Space) California Sacramento CA 32182118 West 6 Idaho Boise ID 1228684 West 6

  9. 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.

  10. 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”

  11. 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…

  12. 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 fieldsize and brings about very nice alignment of columnar data. See figure 9.3 in text.

  13. 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)

  14. 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.

  15. 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.

  16. 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 runtime! (like “testFile.dat”) • Additional features: Can specify a directory and full path as well, such as C:\myDirectory\COP2010\wgabra.txt • Consider:

  17. 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 OpenFileDialogcontrol (whatever you have named it) and we can then have the srdFileobject pointing to the desired Filename to read the data..

  18. Open File Dialog BoxesHow to get there…Project 3 • 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. .

  19. Open File Dialog BoxesHow to get there…Project 3 • When you execute your program, Selectyour 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 YoucanalsoFilter 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.

  20. 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

  21. Open File Dialog Boxes: more

More Related