Lecture 5 Text File I/O; Parsing.

Slides:



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

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Nov 10, Fall 2006IAT 8001 Debugging. Nov 10, Fall 2006IAT 8002 How do I know my program is broken?  Compiler Errors –easy to fix!  Runtime Exceptions.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
Files and Streams CS 21a Chapter 11 of Horstmann.
1 CS2200 Software Development Lecture 36: File Processing A. O’Riordan, 2008 (Includes slides by Lewis/Loftus 2205 and K. Brown )
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Georgia Institute of Technology Speed part 3 Barb Ericson Georgia Institute of Technology May 2006.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
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.
CS 11 java track: lecture 2 This week: more on object-oriented programming (OOP) objects vs. primitive types creating new objects with new calling methods.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
Java Programming Review (Part II) Enterprise Systems Programming.
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.
 Learn about computer files  Use the Path class  Learn about  Streams  Buffers  file organization  Use Java’s IO classes to write to and read from.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Georgia Institute of Technology Making Text for the Web part 2 Barb Ericson Georgia Institute of Technology March 2006.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
CS 116 Object Oriented Programming II Lecture 11 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
For Friday Finish reading chapter 9 WebCT quiz 17.
CHAPTER 3 File Output.
OO Design and Programming II I/O: Reading and Writing
Lecture 5 Text File I/O; Parsing.
CMSC 202 Text File I/O.
Introduction to programming in java
Reading from a file and Writing to a file
Chapter 7 User-Defined Methods.
Class Structure 15-Jun-18.
Streams and File I/O.
University of Central Florida COP 3330 Object Oriented Programming
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
Strings and File I/O.
File Input and Output TOPICS File Input Exception Handling File Output.
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
CHAPTER 5 JAVA FILE INPUT/OUTPUT
Chapter 12 Exception Handling and Text IO
Testing and Exceptions
File Input and Output TOPICS File Input Exception Handling File Output.
Java for Teachers Intermediate
File I/O ICS 111: Introduction to Computer Science I
Unit 6 Working with files. Unit 6 Working with files.
File Handling in Java January 19
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
Exception Handling Contents
LCC 6310 Computation as an Expressive Medium
Lecture 6 Text File I/O Parsing Text CS2012.
Presentation transcript:

Lecture 5 Text File I/O; Parsing

File I/O Databases are the most efficient way to store large amounts of structured data, and accordingly, most live applications use databases for permanent data storage Right now, we are mostly interested in the exceptions to this rule: Applications such as word processors and spreadsheets, whose purpose is to generate specially-formatted documents using data that is not easily converted to database records. Data that must be exchanged easily among many users who don’t necessarily have access to the same DBMS, e.g. information publicly available on the internet 2

The File Class The File class provides an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion. The filename is a string. The File class is a wrapper class for the file name and its directory path. 3

Obtaining file properties and manipulating files 4

File I/O Two types of files are used for I/O Binary Files: to be covered later in CS202 or in CS203 Text Files Data can be read from text files that are rigorously structured. Two common cases: XML (various forms of eXtensible Markup Language) CSV (Comma-Separated Values) 5

Text File I/O Data is stored as text, but we need objects and/or primitive data types Read in strings Parse to the data types you need Use logic to translate the parsed data to the data fields you need Labor-intensive and error prone, yet necessary where data must be widely available for different applications 6

Reading Data Using Scanner 7

Writing Data Using PrintWriter 8

Writing Data Using PrintWriter Get fields called CIN and grade from a list of Student objects and write them to a csv file using a PrintWriter for (Student s: students){ writer.println(s.getCIN() + "," + s.getGrade()); } 9

BufferedWriter A type of PrintWriter that writes data in chunks, rather than one character at a time Set aside a memory buffer, fill it with data, then write it all out, and repeat until finished. This uses system resources more efficiently because writing to the file involves overhead that is not proportional to the amount of data written. Reducing the number of writes makes the process less expensive. 10

Throws/Catch Declaring an exception type with the throws keyword in a method header throws the exception to the calling method, where it must be caught You can also set custom circumstances for an exception using throw(), usually in an if block: throw new NullPointerException( "This will be caught below" ); 12

File Copy 13 import java.io.*; import java.util.*; public class TextFileCopier { public static void main(String args[]) { //... Get two file names from user. System.out.println("Enter a filepath to copy from, and one to copy to."); Scanner in = new Scanner(System.in); //... Create File objects. File inFile = new File(in.next()); // File to read from. File outFile = new File(in.next()); // File to write to //... Enclose in try..catch because of possible io exceptions. try { copyFile(inFile, outFile); } catch (IOException e) { System.err.println(e); System.exit(1); } public static void copyFile(File fromFile, File toFile) throws IOException { Scanner freader = new Scanner(fromFile); BufferedWriter writer = new BufferedWriter(new FileWriter(toFile)); //... Loop as long as there are input lines. String line = null; while (freader.hasNextLine()) { line = freader.nextLine(); writer.write(line); writer.newLine(); //... Close reader and writer. freader.close(); writer.close(); 13

Parsing Parse Definitions From Wiktionary: 1. (linguistics) To resolve into its elements, as a sentence, pointing out the several parts of speech, and their relation to each other by government or agreement; to analyze and describe grammatically. 2. (computing) To split a file or other input into pieces of data that can be easily stored or manipulated. 14

Parsing Parsing input is a common problem in programming. In Object-Oriented Programming, parsing usually involves converting input into individual values which are then used to supply data for variables in objects. This is the first way we will use file storage in our programs. 15

Parse a CSV file package demos; public class Lect4Student{ private String name; private double grade; public Lect4Student(String nameIn, double gradeIn){ name = nameIn; grade = gradeIn; } public String getName(){ return name; public double getGrade(){ return grade; public String toString(){ return(name + " received grade: " + grade); 17

Parse a CSV file package demos; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class StudentParser { private List<Lect4Student> students = new ArrayList<Lect4Student>(); public void showGrades() { for (Lect4Student s : students) { System.out.println(s.toString()); } showAverage(); public int findByName(String name) { for (int counter = 0; counter < students.size(); counter++) { if (students.get(counter).getName().equals(name)) return counter; return -1; public void showAverage() { double total = 0; for (Lect4Student stu : students) total += stu.getGrade(); System.out.println("Class Average: " + total / students.size()); public void readFile() throws IOException { try { System.out.println("Enter a filepath to read from "); Scanner in = new Scanner(System.in); File inFile = new File(in.next()); // File to read from. Scanner freader = new Scanner(inFile); freader.nextLine(); // skip the header String line; String[] fields; String name; double grade; while (freader.hasNextLine()) { line = freader.nextLine(); fields = line.split(","); name = fields[0]; grade = Double.parseDouble(fields[1]); students.add(new Lect4Student(name, grade)); freader.close(); // Close to unlock. in.close(); } catch (IOException e) { System.err.println(e); System.exit(1); 18

Parse a CSV file public void showAverage() { double total = 0; for (Lect4Student stu : students) total += stu.getGrade(); System.out.println("Class Average: " + total / students.size()); } public void readFile() { try { System.out.println("Enter a filepath to read from "); Scanner in = new Scanner(System.in); File inFile = new File(in.next()); // File to read from. Scanner freader = new Scanner(inFile); freader.nextLine(); // skip the header String line; String[] fields; String name; double grade; while (freader.hasNextLine()) { line = freader.nextLine(); fields = line.split(","); name = fields[0]; grade = Double.parseDouble(fields[1]); students.add(new Lect4Student(name, grade)); freader.close(); // Close to unlock. in.close(); } catch (IOException e) { System.err.println(e); System.exit(1); 19

Parse a CSV file while (freader.hasNextLine()) { line = freader.nextLine(); fields = line.split(","); name = fields[0]; grade = Double.parseDouble(fields[1]); students.add(new Lect4Student(name, grade)); } freader.close(); // Close to unlock. in.close(); } catch (IOException e) { System.err.println(e); System.exit(1); 20

Parse a CSV file package demos; public class ParseDemo { public static void main(String args[]) { StudentParser parser = new StudentParser(); parser.readFile(); parser.showGrades(); System.out.println(); String name = "Dennis"; int location = parser.findByName(name); if (location == -1) System.out.println(name + " not found"); else System.out.println(name + " found at index " + location); } 21

Parse a CSV file This technique is not very robust, and it requires tedious coding to write and maintain. Any change in the file format or the type of data we need to parse requires recoding our classes. Solutions: Take everything but the basic parsing functions out of parser. Use parser with other classes that can be supplied arbitrarily and provide the file format info and the type of class to parse to. Adjusting the parser to work with different file formats only involves writing new classes that contain only format-specific information. 2) Binary File I/O Java has built in methods to save entire objects to file and read them back into your application when needed Structure of object is maintained No need to do any parsing or mapping of data fields Taught later in CS 202 22

Composition Compose: to create something by combining other things In programming, Composition occurs when a class includes variables of other classes We have been doing this all along whenever we write classes that contain Strings or Scanners. Several of the lecture examples have contained variables that referred to objects of classes defined in the examples. GradeBook contains an array list of Students Driver from lecture 5 contained a College, which contained a list of Departments, and each department contained an array list of Courses Hierarchies like this can be of any depth.

Desk Check Desk checking or desk tracing is the technique of executing code manually, with paper and pencil. Trace table: a table used to keep track of data values during a desk check (example from Wikipedia) int i, x = 0; for (i = 1; i <= 10; i++) { x = i * 2; }