James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java Writing and reading objects to and from.

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

Lecture 15: I/O and Parsing
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.
Chapter 10 Ch 1 – Introduction to Computers and Java Streams and File IO 1.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
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 Handling and Serialization CSIS 3701: Advanced Object Oriented Programming.
James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java.
James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java.
James Tam Exception handling in Java Java Exception Handling Dealing with errors using Java’s exception handling mechanism.
James Tam Simple file handling in Java Simple File Input And Output Types of Java files Simple file output in Java Simple file input in Java.
Simple Java I/O Part I General Principles. 2 Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
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.
Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
Lecture 7 File I/O (and a little bit about exceptions)‏
Unit 211 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files.
James Tam Simple File Input And Output You will learn how to write to and read from text and serialized files in Java.
Files and Streams CS 21a Chapter 11 of Horstmann.
James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java.
Unit 201 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files.
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.
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
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.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
13-Jul-15 Simple Java I/O Part I General Principles.
15-Jul-15 Simple Java I/O Part I General Principles.
Io package as Java’s basic I/O system continue’d.
פיתוח מונחה עצמים – שפת JAVA קבצים. References קורס "שיטות בהנדסת תוכנה", הפקולטה למדעי המחשב, הטכניון. קורס "מערכות מידע מבוזרות", הפקולטה להנדסת תעשייה.
Java Exception Handling Handling errors using Java’s exception handling mechanism.
Handling errors Exception handling and throwing Simple file processing.
CIS 270—Application Development II Chapter 14—Files and Streams.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
Working with files By the end of this lecture you should be able to: explain the principles of input and output and identify a number of different input.
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.
Java I/O Writing and Reading Objects to File Serialization.
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,
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
Chapter 15 Text Processing and File Input/Output Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
Lecture 5 I/O and Parsing
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.
09/13/12All Rights Reserved - ADVANTEST CORPORATION1 Java 7 Highlights Presented By: Andrey Loskutov.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
Mark Fontenot CSE Honors Principles of Computer Science I Note Set 15.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
Simple File Input And Output You will learn how to write to and read from text and serialized files in Java.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
James Tam Java Exception Handling Handling errors using Java’s exception handling mechanism.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Lesson 8: More File I/O February 5, 2008
Object Writing in files
Simple File Input And Output
I/O Basics.
Accessing Files in Java
Part I General Principles
Streams and File I/O Chapter 9 Chapter 9.
הרצאה 12: קבצים וחריגות (Exceptions)
استفاده از فایلها در جاوا
Simple File Input And Output
Simple File Input And Output
Web Design & Development Lecture 8
ECE 122 April 14, 2005.
Java IO Packages Prepared by Mrs.S.Amudha AP/SWE
David Davenport Spring 2005
Presentation transcript:

James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java Writing and reading objects to and from file (by implementing the Serializable interface)

James Tam Storing Information On Files Types of files Text files Binary files

James Tam Binary files Includes all other types of files (it’s a catch all term for non-binary files) e.g., Interpret the bit pattern as a 16 bit unsigned short Text files Every 8 bits represents a character e.g., ‘0’ = 48, ‘1’ = 49 Text Files ‘0’‘1’

James Tam (You Should Know Why You Can Get Garbage In Text Editors) ÿØÿà JFIF ÿÛ C $.' ",#(7),01444'9=82<.342ÿÛ C 2!! ÿÀ " ÿÄ ÿÄ G !1AQa"2q‘¡#3B±ÁRÑáð$SbrñCs‚46c’5%&t¢²ÿÄ ÿÄ * !1A"2Qa#3qBÿÚ ? òöwá»?xïMÐïäž;[¯7{ÀÀ8Û¸Á Žª;TÑ ñ‹ìt«›{ëˆgó7E`ñ$Ͷ6a´ÊBFNOLãœUöuâ+O ¹Ý À$¬;ÑŸjÞðwŒ´Ív+ÝbõmžA$M§EÚÑ:d=²rËÁÇçŒn‚Œ[èÏi¾ ñ¯§Ã}c§ùÏæþLѤ—>PÌžTlÁåÚ:윎£ßîGˆ¿²?µ?³ÿ áÿ øÝžt~wá÷mó¼Þg— ŸâÛŒsœsZø.4cÀ¾Óu¤Ô£:9»–?â|椻Ùá†Àü}x9©ëVº¯‡l¬Ž­âCk£¦›ø K´Î¹_2C»â+³œ»ÒÞx.´™Zº<âox’,j/a€Ù.¡±.¡yØľR±}œòvàsœ`ÔîOˆ²?µ?³ÿ áÿ øížt~wá÷mó¼Þg— ŸâÛŒsœs^¤|C¤ý;ÏþÐÿ wþTýç÷¾o—

James Tam Reading Text Input From A File File : byte stream FileReaderBufferedReader ‘A’ ‘N’ ‘ char stream String “AN “

James Tam Writing Text Output To A File File : byte stream FileWriterPrintWriter ‘ ‘ ‘N’ ‘A’ char stream “AN “ Primitives, Strings, Objects 1 1 By objects we of course mean references to objects

James Tam An Example Of Simple Input And Output The full example can be found in Unix in the directory: /home/233/examples/fileIO/example1

James Tam Class IntegerWrapper public class IntegerWrapper { private int num; public IntegerWrapper () { num = (int) (Math.random() * 100); } public void setNum (int newValue) { num = newValue; } public int getNum () { return num; }

James Tam Class SimpleIO import java.io.*; public class SimpleIO { public static void main (String [] argv) { IntegerWrapper iw1 = new IntegerWrapper (); IntegerWrapper iw2 = new IntegerWrapper (); String filename = "data"; PrintWriter pw; FileWriter fw; BufferedReader br; FileReader fr;

James Tam Class SimpleIO (2) try { fw = new FileWriter (filename); pw = new PrintWriter (fw); System.out.println("Written to file: " + iw1.getNum()); pw.println(iw1.getNum()); System.out.println("Written to file: " + iw2.getNum()); pw.println(iw2.getNum()); fw.close();

James Tam Class SimpleIO (3) fr = new FileReader(filename); br = new BufferedReader(fr); System.out.println("Read from file: " + br.readLine()); System.out.println("Read from file: " + br.readLine()); fr.close(); }

James Tam Class SimpleIO (4) catch (IOException e) { e.printStackTrace(); }

James Tam Reading Until The End-Of-File Is Reached String filename = "data"; BufferedReader br = null; FileReader fr = null; String temp = null; try { fr = new FileReader(filename); br = new BufferedReader(fr); temp = br.readLine (); while (temp != null) { : : : temp = br.readLine (); } : : :

James Tam Checking For More Specific Error Types String filename = null; BufferedReader br; FileReader fr; boolean fileError = true; while (fileError == true) { try { System.out.print("Enter name of input file: "); filename = Console.in.readWord(); fr = new FileReader(filename); br = new BufferedReader(fr); : : fr.close (); fileError = false; }

James Tam Checking For More Specific Error Types (2) catch (FileNotFoundException e) { System.out.println("File called " + filename + " not in the current directory"); } catch (IOException e) { System.out.println("General file input error occured."); e.printStackTrace(); }

James Tam Writing Objects Out To File: “The Hard Way” The full example can be found in Unix in the directory: /home/233/examples/fileIO/example2 Student object: String firstName String lastName int id Each field is written out to a file individually data.txt Bart Simpson This approach is awkward because: 1.It requires knowledge of all the attributes of the class. 2.If attributes are not simple types or classes which can’t be directly written to file the non-writable attribute must be broken down and written to file on a field-by basis. 3.Some attributes may have to be parsed or converted.

James Tam The Driver Class public class Driver { public static void main (String [] args) { final String FILENAME = "data.txt"; PrintWriter pw; FileWriter fw; BufferedReader br; FileReader fr; Student aStudent = new Student("Bart", "Simpson", ); int tempNum; String tempLine;

James Tam The Driver Class (2) try { fw = new FileWriter (FILENAME); pw = new PrintWriter (fw); pw.println(aStudent.getFirstName()); pw.println(aStudent.getLastName()); pw.println(aStudent.getId()); fw.close(); fr = new FileReader(FILENAME); br = new BufferedReader(fr); aStudent.setFirstName(br.readLine()); aStudent.setLastName(br.readLine()); tempLine = br.readLine(); aStudent.setId(Integer.parseInt(tempLine)); fr.close(); System.out.println(aStudent); }

James Tam The Driver Class (3) catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); }

James Tam Class Student public class Student { private String firstName; private String lastName; private int id; public Student () { firstName = "no name"; lastName = "no name"; id = -1; }

James Tam Class Student (2) public Student (String aFirstName, String aLastName, int anId) { firstName = aFirstName; lastName = aLastName; id = anId; } public String getFirstName () { return firstName; } public String getLastName () { return lastName; } public int getId () { return id; }

James Tam Class Student (3) public void setFirstName (String name) { firstName = name; } public void setLastName (String name) { lastName = name; } public void setId (int anId) { id = anId; } public String toString () { String s = new String (); s = s + "First name: " + firstName + "\n" + "Last name: " + lastName + "\n" + "ID No: " + id + "\n"; return s; }

James Tam Writing Objects Out To File: A Better Way The full example can be found in Unix in the directory: /home/233/examples/fileIO/example3 Write all the data for the class all at once Student object: String firstName String lastName int id Bart Simpson data.txt Object is ‘serialized’ (given a serial number) on the (output) stream Objects of a class can be serialized when the class implements the Serializable interface

James Tam The Driver Class public class Driver { public static void main (String [] args) { final String FILENAME = "data.txt"; try { // Write object to file. ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream(FILENAME)); Student aStudent = new Student("Bart", "Simpson", ); out.writeObject(aStudent); out.close(); aStudent = null;

James Tam The Driver Class (2) ObjectInputStream in = new ObjectInputStream (new FileInputStream(FILENAME)); aStudent = (Student) in.readObject(); System.out.println(aStudent); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }

James Tam The Student Class: Key Difference public class Student implements Serializable { private String firstName; private String lastName; private int id; public Student () { firstName = "no name"; lastName = "no name"; id = -1; }

James Tam Note: The Data File For Serialized Objects Is In Binary Form ¬í?sr? Student’±"‹Ìk?I?idL? artt? Simpson

James Tam Note: Many ‘Container’ Classes Are Serializable Serializable Containers: ArrayList LinkedList Vector : The effect of having a serializable container class is that the entire container can be serialized

James Tam Classes That Don’t Implement The Serializable Interface 1.The contents of the class (data) are confidential. 2.The contents of the class is meaningful only while the program runs.

James Tam You Should Now Know How to write to files with Java classes FileWriter PrintWriter How to reading text information from files with Java classes FileReader BufferedReader How objects can be written to file in a serializable form.