Lecture 6 Text File I/O Parsing Text CS2012.

Slides:



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

Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
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.
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 
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 )
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
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.
1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination 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.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
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,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
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.
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.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
 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.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
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.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
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.
Lesson 8: More File I/O February 5, 2008
Introduction to programming in java
Reading from a file and Writing to a file
Chapter 7 User-Defined Methods.
Class Structure 15-Jun-18.
University of Central Florida COP 3330 Object Oriented Programming
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
Lecture 5 Text File I/O; Parsing.
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
COMPUTER 2430 Object Oriented Programming and Data Structures I
CHAPTER 5 JAVA FILE INPUT/OUTPUT
Accessing Files in Java
Testing and Exceptions
File Input and Output TOPICS File Input Exception Handling File Output.
Topics Introduction to File Input and Output
Java for Teachers Intermediate
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
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.
Topics Introduction to File Input and Output
LCC 6310 Computation as an Expressive Medium
Presentation transcript:

Lecture 6 Text File I/O Parsing Text CS2012

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 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 3

Obtaining file properties and manipulating files 4 4

File I/O Two types of files are used for I/O Binary Files: to be covered later in CS2012 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 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 6

Reading Data Using Scanner 7 7

Writing Data Using PrintWriter 8 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 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 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" ); 11 11

File Copy 12 12 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(); 12 12

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

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

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); 16 16

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); 17 17

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); 18 18

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); 19 19

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); } 20 20

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 21 21