Lecture 5 Text File I/O; Parsing.

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.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
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 )
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.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Georgia Institute of Technology Speed part 3 Barb Ericson Georgia Institute of Technology May 2006.
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.
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.
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.
Text Files and String Processing
 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.
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.
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
File Input / Output.
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.
University of Central Florida COP 3330 Object Oriented Programming
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
Lecture 5 Text File I/O; Parsing.
Building Java Programs
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
Creating and Modifying Text part 2
Accessing Files in Java
File Input and Output TOPICS File Input Exception Handling File Output.
Streams and File I/O Chapter 14.
Topics Introduction to File Input and Output
CSS 161: Fundamentals of Computing
Reading and Writing Text Files
Text I/O.
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 20 GEORGE KOUTSOGIANNAKIS
Topics Introduction to File Input and Output
Java Programming Language
Chapter 12 Exception Handling and Text IO Part 2
Topics Introduction to File Input and Output
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.*; import java.util.*; public class StudentParser { private List<Lect4Student> students; public StudentParser() { students = new ArrayList<Lect4Student>(); } public void showGrades() { for (Lect4Student s : students) { System.out.println(s.toString()); showAverage(); public void showAverage() { double total = 0; for (Lect4Student stu : students) total += stu.getGrade(); System.out.println("Class Average: " + total / students.size()); 18

Parse a CSV file 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); 19

Parse a CSV file package demos; public class ParseDemo { public static void main(String args[]) { StudentParser parser = new StudentParser(); try{ parser.readFile(); } catch (Exception e){e.printStackTrace();} parser.showGrades(); 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 and use it with other classes that can be supplied arbitrarily and provide the file format info and the type of class to parse to. 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