Copyright 2008 by Pearson Education C# File I/O Line by line and token-based file input.

Slides:



Advertisements
Similar presentations
Lecture 15: I/O and Parsing
Advertisements

Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson All rights reserved.
CIS 1068 Program Design and Abstraction
1 Text File I/O Chapter 6 Pages File I/O in an Object-Oriented Language Compare to File I/O in C. Instantiate an ofstream object. Like opening.
Lecture Roger Sutton CO331 Visual Programming 19: Simple file i/o Exceptions – Error handling 1.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 2 - HelloWorld Application: Introduction to.
File I/O 11_file_processing.ppt
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Introduction to Exception Handling and Defensive Programming.
1.  Writing snippets of code that try to use methods (functions) from your program.  Each snippet should test one (and only one) function......by calling.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 BUILDING JAVA PROGRAMS CHAPTER 6 FILE PROCESSING.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
1 BUILDING JAVA PROGRAMS CHAPTER 6 DETAILS OF TOKEN-BASED PROCESSING.
BUILDING JAVA PROGRAMS CHAPTER 6 File Processing.
File Input and Output (I/O) Engineering 1D04, Teaching Session 7.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
Topic 18 file input, tokens Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
Building Java Programs File Processing. 2 Input/output (I/O) import java.io.*; Create a File object to get info about a file on your drive. –(This doesn't.
Text Files and String Processing
FILE PROCESSING. Reading files To read a file, pass a File when constructing a Scanner. Scanner name = new Scanner(new File(" file name ")); Example:
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
CSC 298 Streams and files.
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: 6.1 – 6.2, 5.4.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson All rights reserved.
File Output Writing data out to a file 1. Output to files  StreamWriter : An object in the System.IO namespace that lets you print output to a destination.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Eight: Streams Slides by Evan Gallagher.
File - CIS 1068 Program Design and Abstraction
CSc 110, Autumn 2017 Lecture 19: While loops and File Input
2.5 Another Java Application: Adding Integers
Building Java Programs
Building Java Programs
File Input and Output TOPICS File Input Exception Handling File Output.
Building Java Programs
CSc 110, Autumn 2017 Lecture 18: While loops and File Input
File Input and Output TOPICS File Input Exception Handling File Output.
CSc 110, Autumn 2016 Lecture 16: File Input.
Topics Introduction to File Input and Output
Building Java Programs
Building Java Programs Chapter 6
Building Java Programs Chapter 6
CS 106A, Lecture 10 File Reading
Adapted from slides by Marty Stepp and Stuart Reges
Input/output (I/O) import java.io.*;
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
File Input and Output.
Building Java Programs
Input/output (I/O) import java.io.*;
Input/output (I/O) import java.io.*;
Building Java Programs
Building Java Programs
Building Java Programs
Input/output (I/O) import java.io.*;
Topics Introduction to File Input and Output
Chapter 6 Lecture 6-1: File Input with Scanner reading: 6.1 – 6.2, 5.4
Building Java Programs
Presentation transcript:

Copyright 2008 by Pearson Education C# File I/O Line by line and token-based file input

Copyright 2008 by Pearson Education 2 Input/output (I/O) using System.IO; Create a FileInfo object to get info about a file on disk. (This doesn't actually create a new file on the hard disk.) FileInfo f = new FileInfo(“Files\\example.txt"); if (f.Exists && f.Length > 1000) { f.Delete(); } Method nameDescription Delete() removes file from disk MoveTo( filename ) moves and/or changes name of file Property nameDescription Exists whether this file exists on disk Name returns file's name Length returns number of bytes in file

Copyright 2008 by Pearson Education 3 Type of Files Binary files Can contain arbitrary patterns of bits (data) We will NOT be dealing with these Include program.EXE's,.CLASS files, image files (PNG, GIF, JPEG, etc), video files, etc, etc. Text Files Have ONLY text inside them Includes anything you made using Notepad, source code files (i.e., files ending in.cs,.java,.cpp), HTML web pages (.html), XML, most-if-not-all Unix/Linux configuration files, etc, etc

Copyright 2008 by Pearson Education 4 Reading files To read a file, call OpenText on a FileInfo object. FileInfo file = new FileInfo("Files\\example.txt"); TextReader name = file.OpenText(); or, even better: TextReader name = new StreamReader("Files\\example.txt");

Copyright 2008 by Pearson Education 5 Closing files You will need to dispose of the file when you’re done with it: TextReader name = new StreamReader("Files\\example.txt"); // The program reads the file here name.Dispose(); C# provides using, which will call dispose for you: using( TextReader name = new "Files\example.txt") ) { // The program reads the file here } name.Dispose() called automatically on exit, no matter how you exit (reach the closing }, return statement, throw an exception, etc, etc)

Copyright 2008 by Pearson Education 6 File paths absolute path: specifies a drive or a top "/" folder C:/Documents/smith/hw6/input/data.csv Windows can also use backslashes to separate folders. relative path: does not specify any top-level folder names.dat input/kinglear.txt Assumed to be relative to the current directory: FileInfo file = new FileInfo("data/readme.txt"); If our program is in H:/hw6, FileInfo will look for H:/hw6/data/readme.txt You can use.. to move up a folder level: with../ hw3/data/readme.txt FileInfo will look for H:/hw3/data/readme.txt

Copyright 2008 by Pearson Education 7 The following program crashes when run: public void Slide_07() { using (TextReader t = new StreamReader("missing_file.txt") ) { string s = t.ReadLine(); } The following error occurs: Unhandled Exception: System.IO.FileNotFoundException: Could not find file 'E:\path\to\program\missing_file.txt'. File name: 'E:\path\to\program\missing_file.txt' at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at PCE_StarterProject.SlideExamples.Slide_05() in E:\path\to\program\Student_Answers.cs:line 76 at PCE_StarterProject.Program.Main(String[] args) in E:\path\to\program\Student_Answers.cs:line 30 Possible error w/ files

Copyright 2008 by Pearson Education 8 Exceptions exception: An object representing a runtime error. dividing an integer by 0 calling charAt on a String and passing too large an index trying to read a file that does not exist We say that a program with an error "throws" an exception. It is also possible to "catch" (handle or fix) an exception. We will not be catching any exceptions in this topic

Copyright 2008 by Pearson Education 9 Input tokens token: A unit of user input, separated by whitespace. We can split a file's contents into tokens. If an input file contains the following: "John Smith" We can interpret the tokens as the following types: TokenType(s) 23int, double, String 3.14double, String "JohnString Smith"String

Copyright 2008 by Pearson Education 10 Line-Based File Parsing Consider a file numbers.txt that contains this text: (Note that means a blank space, \t means a tab) We can think of the file's contents like so: 308.2\n7.4\n3.9\n\t-15.4\n\n We can get each line (using the TextReader.ReadLine()), then deal with each line individually

Copyright 2008 by Pearson Education 11 File input question Recall the input file numbers.txt : Write a program that reads the lines from the file and prints each one followed by a < sign (so it's clear where the line ends)(note the blank line at the end of the output) 308.2< 7.4< 3.9 < < < \t-15.4

Copyright 2008 by Pearson Education 12 public void Slide_12() { using (TextReader file = new StreamReader("Files/numbers.txt")) { for (int i = 0; i < 5; i++) { string sLine = file.ReadLine(); Console.WriteLine("{0}<", sLine ); } } } File Input Answer

Copyright 2008 by Pearson Education 13 File input question Recall the input file numbers.txt : Write a program that reads the values from the file and prints them along with their sum. number = number = 7.4 number = 3.9 number = Sum = \t-15.4

Copyright 2008 by Pearson Education 14 Testing for valid input All basic data types offer a version of TryParse: If given a valid string (Int32, Double, short, etc) each one will change it's second parameter to be that value and return true If given an invalid string (Int32, Double, short, etc) each one will change it's second parameter to be zero and return false MethodDescription Int32.TryParse us/library/f02979c7.aspx Double.TryParse us/library/994c0zb1.aspx short.TryParse aka Int16.TryParse us/library/9hh1awhy.aspx

Copyright 2008 by Pearson Education 15 File Input Answer public void Slide_15() { using (TextReader file = new StreamReader("Files/numbers.txt")) { double sum = 0.0; for( int i = 0; i < 5; i++) { string sLine = file.ReadLine(); double dNum; if (Double.TryParse(sLine, out dNum)) { sum += dNum; Console.WriteLine("number = {0}", dNum); } } Console.WriteLine("Sum = {0}", sum); } }

Copyright 2008 by Pearson Education 16 Reading an entire file Suppose we want our program to process the entire file. (It should work no matter how many values are in the file.) number = number = 7.4 number = 3.9 number = number = 4.7 number = 5.4 number = 2.8 Sum = \t

Copyright 2008 by Pearson Education 17 Reading an entire file answer public void Slide_17() { using (TextReader file = new StreamReader("Files/numbers2.txt")) { double sum = 0.0; string sLine; sLine = file.ReadLine(); while (sLine != null) { double dNum; if (Double.TryParse(sLine, out dNum)) { sum += dNum; Console.WriteLine("number = {0}", dNum); } sLine = file.ReadLine(); } Console.WriteLine("Sum = {0}", sum); } }

Copyright 2008 by Pearson Education 18 File input question 3 Test the program to make sure that it handles files that contain non-numeric tokens (by skipping them). For example, it should produce the same output as before when given this input file, numbers3.txt : hello oops 7.4 bad 3.9 stuff :-) 308.2hello oops7.4 bad3.9stuff

Copyright 2008 by Pearson Education 19 File input answer 3 public void Slide_19() { char[] delimiters = { ' ', '\t' }; using (TextReader file = new StreamReader("Files/numbers3.txt")) { double sum = 0.0; string sLine = file.ReadLine(); while (sLine != null) { string[] tokensFromLine = sLine.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); foreach (string token in tokensFromLine) { double dNum; if (Double.TryParse(token, out dNum)) { sum += dNum; Console.WriteLine("number = {0}", dNum); break; // out of foreach } } sLine = file.ReadLine(); } Console.WriteLine("Sum = {0}", sum); }}

Copyright 2008 by Pearson Education 20 Election question Write a program that reads a file poll.txt of poll data. Format: State Obama% McCain% ElectoralVotes Pollster CT Oct U. of Connecticut NE Sep Rasmussen AZ Oct Northern Arizona U. The program should print how many electoral votes each candidate leads in, and who is leading overall in the polls. Obama: 7 votes McCain: 15 votes Overall: McCain

Copyright 2008 by Pearson Education 21 Election answer public void Slide_21() { char[] delimiters = { ' ', '\t' }; int obamaVotes = 0, mccainVotes = 0, eVotes = 0; using (TextReader t = new StreamReader("Files/poll.txt")) { string sLine = t.ReadLine(); while (sLine != null) { string[] tokens = sLine.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length < 5) { Console.WriteLine("Did not find the expected number of items on line:\n\t{0}", sLine); sLine = t.ReadLine(); continue; }

Copyright 2008 by Pearson Education 22 Election answer int obama; if (!Int32.TryParse(tokens[1], out obama)) { Console.WriteLine("Obama's votes not formatted properly on line\n\t{0}", sLine); sLine = t.ReadLine(); continue; } int mccain; if (!Int32.TryParse(tokens[2], out mccain)) { Console.WriteLine("McCain's votes not formatted properly on line\n\t{0}", sLine); sLine = t.ReadLine(); continue; } if (!Int32.TryParse(tokens[3], out eVotes)) { Console.WriteLine("Electoral votes not formatted properly on line\n\t{0}", sLine); sLine = t.ReadLine(); continue; }

Copyright 2008 by Pearson Education 23 Election answer if (obama > mccain) obamaVotes += eVotes; else if (mccain > obama) mccainVotes += eVotes; // on tie neither candidate gets the votes sLine = t.ReadLine(); } // end of while } Console.WriteLine("Obama: {0} votes", obamaVotes); Console.WriteLine("McCain: {0} votes", mccainVotes); if (obamaVotes > mccainVotes) Console.WriteLine("Overall: Obama"); else Console.WriteLine("Overall: McCain"); }

Copyright 2008 by Pearson Education 24 Token-Based File Parsing Consider a file numbers.txt that contains this text: (Note that means a blank space, \t means a tab) We can think of the file's contents like so: \nabc3.9\n\t-15.4\n\n Get ALL the lines (using the TextReader.ReadToEnd()), use the String.Split method to break the string into an array of individual tokens, then parse (convert) the tokens one by one abc

Copyright 2008 by Pearson Education 25 File input question 5 Test the program to make sure that it handles files that contain non-numeric tokens (by skipping them). For example, it should produce the same output as before when given this input file, numbers4.txt : hello oops 7.4 bad 3.9 stuff :-)

Copyright 2008 by Pearson Education 26 Token-Based Parsing Answer public void Slide_26() { char[] delimiters = { ' ', '\t', '\n', '\r' }; using (TextReader file = new StreamReader("Files/numbers4.txt")) { double sum = 0.0; string sFile = file.ReadToEnd(); string[] tokensFromFile = sFile.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); foreach (string token in tokensFromFile) { double dNum; if (Double.TryParse(token, out dNum)) { sum += dNum; Console.WriteLine("number = {0}", dNum); } } Console.WriteLine("Sum = {0}", sum); } }

Copyright 2008 by Pearson Education 27 Visual Studio Details You will need to set the current working directory for your programs In Solution Explorer: Right-click on project, then Properties Left-hand column: click on 'Debug' Working Directory is about ½ way down – use the... button to browse for 03_PCE_StudentCode Notice that it puts an absolute path into the directory, and not a relative directory  All the files you need for this week's PCEs are stored in the 'Files' sub folder of the starter project