Two Ways to Store Data in a File  Text format  Binary format.

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Lecture 15: I/O and Parsing
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
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.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12 File Input and Output.
Lecture 7 File I/O (and a little bit about exceptions)‏
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
Streams CSC 171 FALL 2004 LECTURE 22. Make up exam Friday 12/3 11AM-12:10PM.
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.
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.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Java I/O Input: information brought to program from an external source
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Use JFileChooser F Text Input.
Two Ways to Store Data in a File Text format Binary format.
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.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Chapter 17 Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams  Use JFileChooser F Text Input.
Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console.
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.
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
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.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
The Java I/O Classes and Interfaces cont’d
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
CHAPTER 15 STREAMS. CHAPTER GOALS To be able to read and write files To become familiar with the concepts of text and binary files To be able to read.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.
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.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
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.
Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Parsing Text Files F Random.
Chapter 15: Input and Output
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
java.io supports console and file I/O
Fundamental of Java Programming
IO in java.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
IO in java.
Chapter 17 Input and Output
OO Design and Programming II I/O: Reading and Writing
Object Writing in files
I/O Basics.
Streams and File I/O Chapter 9 Chapter 9.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Web Design & Development Lecture 8
David Davenport Spring 2005
Presentation transcript:

Two Ways to Store Data in a File  Text format  Binary format

Text Format Information stored as a sequence of characters Characters are stored as their ASCII equivalent - int value stored as ‘1’ ‘2’ ‘3’ ‘4’ ‘5’ 5 bytes bytes A text file is ‘readable’ by humans. Java classes ‘Reader’ and ‘Writer’ (and their subclasses) are for use with text files.

Text I/O  In Java, characters are stored using UNICODE.  Reader objects read characters in the current O.S. format, and convert them to UNICODE storage format.  Writer objects convert the UNICODE stored data to character encoding used by the current O.S.  Reader and Writer are abstract classes

Text Input READER class is an abstract class which is: extended by InputStreamReader which is extended by FileReader extended by BufferedReader Reader class provides abstract methods which will be implemented specifically by all subclasses InputStreamReader object reads bytes from an input stream and decodes them into characters, using the platform’s charset (ASCII for Windows). These characters are converted to UNICODE for storage. read() reads one character (number of bytes depends on charset) FileReader object inherits InputStreamReader capabilities, but the stream is a file. BufferedReader object is a wrapper for any InputStreamReader (including FileReader), and provides buffering (ie. handles multiple char reads and provides a string)

Text one char at a time Text one char at a time  Create a InputStreamReader object Constructor takes an input stream, which may Constructor takes an input stream, which may be keyboard, network connection, any input source be keyboard, network connection, any input source InputStreamReader in = new InputStreamReader(System.in); InputStreamReader in = new InputStreamReader(System.in);  InputStreamReader extends the Reader class, implementing input methods specifically for files  Use its read method to read a single character o returns the next char as an int o or the integer -1 at end of input  Test for -1 to determine if a char was read

Reading one char at a time…. InputStreamReader reader = new InputStreamReader(System.in); InputStreamReader(System.in); char c; //Java chars are UNICODE int next = reader.read() ; //byte read and if (next != -1) c = (char)next(); c = (char)next(); // process c // process c next = reader.read() ; } //See demo testISReader.java

Reading one line at a time…. InputStreamReader in = new InputStreamReader(System.in);//input is from keyboard InputStreamReader(System.in);//input is from keyboard BufferedReader bin = new BufferedReader(in); BufferedReader bin = new BufferedReader(in); String val; String val; val = bin.readLine(); // get one string from keyboard val = bin.readLine(); // get one string from keyboard while(val != null) { //while user does not enter CTRL Z while(val != null) { //while user does not enter CTRL Z System.out.println( val ); System.out.println( val ); System.out.flush(); //output any lines waiting to be printed System.out.flush(); //output any lines waiting to be printed val = bin.readLine(); val = bin.readLine(); } //See demo testBISReader.java

Text one char at a time from a file Text one char at a time from a file  Create a FileReader object  FileReader extends the Reader class, implementing input methods specifically for files  Use its read method to read a single character o returns the next char as an int o or the integer -1 at end of input  Test for -1 to determine if a char was read  Close the file when done

Reading one char at a time from file…. FileReader reader = new FileReader("input.txt"); FileReader("input.txt"); char c; //Java chars are UNICODE int next = reader.read() ; //byte read and if (next != -1){ c = (char)next(); c = (char)next(); next = reader.read(); next = reader.read();reader.close(); // see testFileReader.java // see testFileReader.java

Reading Text Line by Line Create a BufferedReader object (pass a FileReader object to constructor) FileReader object to constructor) objects of type BufferedReader can objects of type BufferedReader can group characters – ‘buffer’ them group characters – ‘buffer’ them method readLine() available, to provide file data 1 line at a time (the method handles reading the characters from the FileReader for you) readLine() returns the next line of file (as a String), or null if none exists

//Reads first line from file named input.txt // line is expected to contain a double value FileReader reader = new FileReader("input.txt"); BufferedReader in = new BufferedReader(reader); String inputLine = in.readLine(); double x = Double.parseDouble(inputLine);

//Reads and all lines from file // and writes them to console import java.io; public class demo{ public static void main(String[] args)throw IOException{ public static void main(String[] args)throw IOException{ FileReader reader = new FileReader("input.txt"); FileReader reader = new FileReader("input.txt"); BufferedReader in = new BufferedReader(reader); BufferedReader in = new BufferedReader(reader); String line = in.readLine(); String line = in.readLine(); While (line != null){ While (line != null){ System.out.println(line); System.out.println(line); line = in.readLine(); line = in.readLine(); } in.close(); in.close(); }}

Text Output WRITER class is an abstract class which is: extended by OutputStreamWriter which is extended by FileWriter extended by PrintWriter Writer class provides abstract methods which will be implemented specifically by all subclasses OutputStreamWriter object writes bytes to an output stream and encodes them into characters, using the platform’s charset (ASCII for Windows). These characters are converted from stored UNICODE write(char) writes one character (number of bytes written depends on charset) Object is buffered, may be flushed FileWriter object is inherits OutputStreamWriter capabilities, but the stream is a file PrintWriter object is a wrapper for any OutputStreamWriter, and provides buffering (ie. handles multiple char writes and provides a string)

Write a Character to File FileWriter class implements Writer methods specifically for files. FileWriter class implements Writer methods specifically for files. FileWriter writer = new FileWriter writer = new FileWriter("output.txt"); FileWriter("output.txt"); char c =‘a'; char c =‘a'; writer.write(c); writer.write(c); writer.close(); writer.close();

Writing Strings to Text Files A PrintWriter object handles the ‘unbuffering’ of data for output file writer A PrintWriter object handles the ‘unbuffering’ of data for output file writer Create PrintWriter object (pass FileWriter object to constructor) Create PrintWriter object (pass FileWriter object to constructor) PrintWriter class provides ‘println’ method which accepts String and uses FileWriter to print one char at a time. PrintWriter class provides ‘println’ method which accepts String and uses FileWriter to print one char at a time. FileWriter writer = new FileWriter(“output.txt”) FileWriter writer = new FileWriter(“output.txt”) PrintWriter out = new PrintWriter(writer); PrintWriter out = new PrintWriter(writer);

//use PrintWriter object to output data to file output.txt FileWriter writer = new FileWriter(“output.txt”) PrintWriter out = new PrintWriter(writer); out.println(29.95); out.println(new Rectangle(5,10,15,25)); out.println("Hello, World!");

StringTokenizer Class When reading a line of text, we get a single long string. Suppose our line of text looked something like: John|Doe|16|1998 In other words, the string contained know ‘delimiters’, and we wanted to access the ‘pieces’ between these delimiters. Java.util package provides a class to help here: StringTokenizer Methods: StringTokenizer(String theline, String delimiters) Methods: StringTokenizer(String theline, String delimiters) boolean hasMoreTokens() boolean hasMoreTokens() String nextToken() String nextToken() int countTokens() int countTokens() see file CountTHE.java see file CountTHE.java

Binary Format More compact and efficient int stored using binary representation: bytes 4 bytes Java abstract classes I nputStream and OutputStream (and their subclasses) provide methods for reading and writing these types of files

Binary File I/O  In Java, an object from which we can read a sequence of bytes is called an input stream.  An object to which we can write a sequence of bytes is called an output stream.  I/O streams have beginning, end, and are read sequentially.  InputStream and OutputStream are abstract classes.

InputStream class has an abstract method abstract int read() abstract int read() // reads and returns one byte // reads and returns one byte An abstract method is an method which MUST be implemented by any extending class. The idea is that the extending class provides specifics… OutputStream class has an abstract method OutputStream class has an abstract method abstract void write(int b); abstract void write(int b); // writes one byte to output // writes one byte to output Java provides many stream classes which extend from InputStream and OutputStream that let you work with data in the forms that that let you work with data in the forms that you normally use………. you normally use……….

Byte Streams Byte Streams InputStream is extended by FileInputStream which is used for byte based input from a file OutputStream is extended by FileOutputStream which is used for byte based output to a file Both of these classes implement read and write methods as specified in their abstract super classes. see file ByteIO.java

Input Byte Streams InputStream is extended by FilterInputStream FilterInputStream is extended by DataInputStream FilterInputStream acts as a ‘wrapper’ for an InputStream objects, which it uses as its basic source of data. Methods of FilterInputStream objects simply pass requests to the InputStream objetct. Each subclass of FilterInputStream transforms the data along the way, or provides some additional functionality. For example, DataInputStream ‘wraps’ a InputStream object and assembles bytes read into numerical types. ** readInt, readDouble, readBoolean are just some of the methods available with a DataInputStream object See file DataByteIO.java See file DataByteIO.java

Input Byte Streams InputStream is extended by FilterInputStream FilterInputStream is extended by BufferedInputStream Another subclass of FilterInputStream is BufferedInputStream. BufferedInputStream ‘wraps’ a InputStream object and provides ‘buffering’ for efficiency. BufferedInputStream overloads ‘read’ so that in addition to one byte at a time, one byte array can be read. // buffered input // buffered input BufferedInputStream bin = new BufferedInputStream(new InputStream(“file.txt”)); // add another layer so that DataInputStream object will not do individual reads // add another layer so that DataInputStream object will not do individual reads // for each byte, but use the buffered reads // for each byte, but use the buffered reads DataInputStream dbin = new DataInputStream(bin);

Output Byte Streams FilterOutputStream extends OutputStream (Subclasses may be superclasses themselves) PrintStream extends FilterOutputStream FilterOutputStream acts as a ‘wrapper’ for an OutputStream object, which it uses as its basic depository of data. Methods of FilterOutputStream simply pass requests to the OutputStream objetct. PrintStream ‘wraps’ a OutputStream and provides an accurate display of data types to the output, in addition to buffering. PrintStream also provides the overloaded println, which accepts String and byte[] parameters, as well as byte. which accepts String and byte[] parameters, as well as byte. System.out, is an object of type PrintStream, which is provided by the System class in the java.lang input. System.out ‘wraps’ the OutputStream object representins the console.

FILE OBJECTS provide methods which allow the creation, deletion, and other file manipulation/status methods… FileInputStream and FileReader constructors are overloaded to accept a File object. The file object will allow you to check the status of a file before you open it!! File f = new File(“in.txt”); if ( ! f.exists() ) if ( ! f.exists() ) System.out.println(“file does not exist”); System.out.println(“file does not exist”); else if ( ! F.canRead() ) else if ( ! F.canRead() ) System.out.println(“file cannot be read”); System.out.println(“file cannot be read”); else { else { FileInputStream in = new FileInputStream(f); FileInputStream in = new FileInputStream(f); BufferedInputStream bufIn = new BufferedInputStream(in); BufferedInputStream bufIn = new BufferedInputStream(in); int bb = bufIn.read(); int bb = bufIn.read();

A JFileChooser Dialog

File Dialogs Use JFileChooser to let a user supply a file name through a file dialog Use JFileChooser to let a user supply a file name through a file dialog Construct a file chooser object Construct a file chooser object Call its showOpenDialog or showSaveDialog method Call its showOpenDialog or showSaveDialog method (Specify null or the user interface component over which to pop up the dialog ) (Specify null or the user interface component over which to pop up the dialog ) If the user chooses a file: JFileChooser.APPROVE_OPTION is returned If the user chooses a file: JFileChooser.APPROVE_OPTION is returned If the user cancels the selection: JFileChooser.CANCEL_OPTION is returned If the user cancels the selection: JFileChooser.CANCEL_OPTION is returned If a file is chosen, use GetSelectedFile method to obtain a File object describing the file If a file is chosen, use GetSelectedFile method to obtain a File object describing the file

Code to Use a JFileChooser JFileChooser chooser new JFileChooser(); FileReader in; if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = chooser.getSelectedFile(); File selectedFile = chooser.getSelectedFile(); in = new FileReader(selectedFile); in = new FileReader(selectedFile);}else in = null; in = null; // see file testDialog.java // see file testDialog.java

Mark and Reset The abstract classes InputStream and Reader provide: The abstract classes InputStream and Reader provide: void mark (int byteLimit) void mark (int byteLimit) * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at the last marked position so that subsequent reads re-read the same bytes. * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at the last marked position so that subsequent reads re-read the same bytes. * byteLimit is the number of bytes that can be read before this mark becomes invalid * byteLimit is the number of bytes that can be read before this mark becomes invalid void reset() void reset() * repositions stream to position when mark was last called * repositions stream to position when mark was last called boolean markSupported () indicates if a stream supports these methods

int[] intList; int[] intList; intList = new int[100]; intList = new int[100]; //this file contains one number 66 //this file contains one number 66 FileReader file = new FileReader("number.txt"); FileReader file = new FileReader("number.txt"); BufferedReader ifile = new BufferedReader(file); BufferedReader ifile = new BufferedReader(file); // all array elements are initialized to 66 // all array elements are initialized to 66 ifile.mark(5); ifile.mark(5); for (int i = 0; i<100; i++){ for (int i = 0; i<100; i++){ String sVal = ifile.readLine(); String sVal = ifile.readLine(); ifile.reset(); ifile.reset(); intList[i] = Integer.parseInt(sVal); intList[i] = Integer.parseInt(sVal); }

Object Output Another byte (binary) I/O class which extends from OutputStream is ObjectOutputStream ObjectOutputStream class can save entire objects to disk ! ObjectOutputStream class can save entire objects to disk ! Objects that are written to an object stream must belong to a class that implements the Serializable interface. class Coin implements Serializable class Coin implements Serializable {......} ** Serializable interface has no methods. ** Serializable interface has no methods.

Serializable  Objects that are written to an object stream must belong to a class that implements the Serializable interface. class Coin implements Serializable class Coin implements Serializable {......} ** Serializable interface has no methods. ** Serializable interface has no methods.

ObjectOutputStream methods Stream does not just write objects …….. write( ) - writes a byte writeInt(int) - writes a 32 bit int writeDouble(double) - writes a 64 bit double writeChar(char) - writes a 16 bit char writeObject(Object) - writes the specified object to the output stream (if Serializable) the output stream (if Serializable) close() - closes stream

Writing an Object to a File OutputStream os = new FileOutputStream("data.txt"); OutputStream os = new FileOutputStream("data.txt"); ObjectOutputStream out = new ObjectOutputStream(os); ObjectOutputStream out = new ObjectOutputStream(os); ArrayList boxlist = new ArrayList (); ArrayList boxlist = new ArrayList (); boxlist.add(new Box(5)); boxlist.add(new Box(5)); boxlist.add(new Box(17)); boxlist.add(new Box(17)); boxlist.add(new Box(20)); boxlist.add(new Box(20)); out.writeObject(boxlist); out.writeObject(boxlist); out.close(); out.close();

Object Input  Another byte (binary) I/O class which extends from InputStream is ObjectInputStream ObjectInputStream ObjectInputStream class can read from a file, written by ObjectOutputStream ObjectInputStream class can read from a file, written by ObjectOutputStream (Data must by read with respect to datatype and order with which it was written)

ObjectInputStream methods read( ) - reads a byte readInt() - reads a 32 bit int readDouble() - reads a 64 bit double readChar() - reads a 16 bit char readObject( ) - reads the specified object to the input stream (if Serializable) the input stream (if Serializable) close() - closes stream

Reading from File containing Objects public static void main(String[] args) throws IOException,ClassNotFoundException { public static void main(String[] args) throws IOException,ClassNotFoundException { InputStream is = new FileInputStream("data.txt"); InputStream is = new FileInputStream("data.txt"); ObjectInputStream in = new ObjectInputStream(is); ObjectInputStream in = new ObjectInputStream(is); ArrayList boxlist = (ArrayList ) in.readObject(); ArrayList boxlist = (ArrayList ) in.readObject(); for (int i = 0; i< boxlist.size(); i++) for (int i = 0; i< boxlist.size(); i++) System.out.println(boxlist.get(i)); System.out.println(boxlist.get(i)); in.close(); in.close();

Random.vs. Sequential Access Sequential accessSequential access o A file is processed a byte at a time. Random accessRandom access o Allows access at arbitrary locations in the file