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.

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

1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
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.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
III. Streams. Introduction Often a program needs to bring in information from an external source or to send out information to an external destination.
Lecture 31 File I/O -Part 2 COMP1681 / SE15 Introduction to Programming.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
Algorithm Programming I/O via Java Streams Bar-Ilan University תשס"ח by Moshe Fresko.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 18 Binary I/O.
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.
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.
Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with.
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 19 Binary I/O.
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.
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 16 Simple Input and Output 与人玫瑰,手有余香.
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.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
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,
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.
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.
L5: Input & Output COMP206, Geoff Holmes and Bernhard Pfahringer.
Two Ways to Store Data in a File  Text format  Binary format.
Java Input/Output. Reading standard input Surprisingly complicated (GUI focus) Old-fashioned way: BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Binary I/O.
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.
1 Chapter 19 Binary I/O. 2 Motivations F Data stored in a text file – is represented in human-readable form –Text file –Readable –Java source programs.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Files in Java 1.
1 Chapter 16 Simple Input and Output. 2 Objectives F To discover file properties, delete and rename files using the File class (§16.2). F To understand.
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.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
Java I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Java IO Exploring the java.io package and living to talk about it.
Chapter 10: I/O Streams Input Streams Output Streams
The Java IO System Different kinds of IO Different kinds of operations
Fundamental of Java Programming
IO in java.
Sequential files creation & writing
IO in java.
Chapter 17 Input and Output
OO Design and Programming II I/O: Reading and Writing
Chapter 17 Binary I/O.
Object Writing in files
I/O Basics.
Chapter 17 Binary I/O 1.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Programming in Java Files and I/O Streams
Streams and File I/O Chapter 9 Chapter 9.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Chapter 16 Simple Input and Output
Files and Streams in Java
Presentation transcript:

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 F Object Streams

Streams F A stream is an abstraction of the continuous one-way flow of data.

Stream Classes F The stream classes can be categorized into two types: byte streams and character streams. a) The InputStream/OutputStream class is the root of all byte stream classes. b) The Reader/Writer class is the root of all character stream classes.  The subclasses of InputStream/ OutputStream are analogous to the subclasses of Reader/Writer. F In all, over 40 classes are used to provide input and output.

A) Byte Stream Classes

B) Character Stream Classes

Abstract InputStream Class F abstract int read() throws IOException read the next byte and returns its value, an int in range ; at the end returns -1. F int read(byte[] b) throws IOException Read up to b.length bytes into array b, returns b.length or the number of bytes read, or returns -1 at the end of the stream.  void close() throws IOException F int available() throws IOException Returns the number of bytes that can be read form the input stream. F long skip(long n) throws IOException Skip over and discard n bytes of data from the input stream.

Abstract Reader Class The Reader class is similar to the InputStream class. The methods in Reader are subject to character interpretation. F abstract int read() throws IOException F int read(char b[]) throws IOException F void close() throws IOException F void skip(long n) throws IOException

Abstract OutputStream Class F abstract void write(int b) throws IOException F void write(byte[] b) throws IOException F void close() throws IOException F void flush() throws IOException

Abstract Writer Class F abstract void write(char b) throws IOException F void write(char[] b) throws IOException F void close() throws IOException F void flush() throws IOException

The File Class  The File class is a wrapper class for the file name.  The File class does not tell us how to read or write information in files.  The File class is used to check properties of files, such as whether the file exists, or is readable, or is updateable.

The File Class  The statement creates a File object: File MyFile = new File(“C:\myData\in.data”); F Methods String getName(); String getPath(); // Get full path of the file String getAbsolutePath(); String getParent(); // // Get the directory that contains the file int getLength(); boolean exists(); boolean canWrite(); boolean canRead(); boolean isDirectory(); boolean isFile(); boolean delete();

Processing External Files You must use file streams to read from or write to a disk file.  You can use FileInputStream or FileOutputStream for byte streams.  You can use FileReader or FileWriter for character streams.

File I/O Stream Constructors Constructing instances of FileInputStream, FileOutputStream, FileReader, and FileWriter from file names: public FileInputStream(String filenameString); public FileInputStream(File file); public FileOutputStream(String filenameString); public FileOutputStream(File file); public FileReader(String filenameString); public FileReader(File file); public FileWriter(String filenameString); public FileWriter(File file);

Example of File I/O Stream Constructors FileInputStream infile = new FileInputStream("in.dat"); FileInputStream infile = new FileInputStream(file); FileOutputStream outfile = new FileInputStream("in.dat"); FileOutputStream outfile = new FileInputStream(file); FileReader infile = new FileReader("in.dat"); FileReader infile = new FileRader(file); FileWriter outfile = new FileWriter("in.dat"); FileWriter outfile = new FileWriter(file);

Example Processing External Files

Example: Copy External Files import java.io.*; public class CopyFile { public static void main(String[] args) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(new File(args[0]); fos = new FileOutputStream(new File(args[1]); while((int r = fis.read() != -1) { fos.write((byte)r); } } // to be continued...

Example: cont.... catch (FileNotFoundException ex) {... } catch (IOException ex) {... } finally { try { if(fis != null) fis.close(); if(fos != null) fos.close(); } catch (IOException ex) { } } }// main }// class

Data Streams for primitive types  The data streams ( DataInputStream and DataOutputStream ) read and write Java primitive types in a machine-independent fashion F It enables you to write a data file in one machine and read it on another machine that has a different operating system or file structure. F Data streams are wrappers for on existing input and output streams: DataInputStream dis = new DataInputStream(inStream);

DataInputStream Methods F byte readByte() throws IOException F short readShort() throws IOException F int readInt() throws IOException F long readLong() throws IOException F float readFloat() throws IOException F double readDouble() throws IOException F char readChar() throws IOException F boolean readBoolean() throws IOException F String readUTF() throws IOException

DataOutputStream Methods F void writeByte(byte b) throws IOException F void writeShort(short s) throws IOException F void writeInt(int i) throws IOException F void writeLong(long l) throws IOException F void writeFloat(float f) throws IOException F void writeDouble(double d) throws IOException F void writeChar(char c) throws IOException F void writeBoolean(boolean b) throws IOException F void writeBytes(String l) throws IOException F void writeChars(String l) throws IOException F void writeUTF(String l) throws IOException

Example: Using Data Streams

Data I/O Stream Constructors F DataInputStream in = new DataInputStream(inpStream); DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); Creates a data input stream for file in.dat. F DataOutputStream out=new DataOutputStream(outStream); DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat")); Creates a data output stream for file out.dat.

Example: 1. Processing Data Streams import java.io.*; public class TestDataStream { public static void main(String[] args) { DataInputStream dis = null; DataOutputStream dos = null; // Construct a temp file File tempFile = new File(“mytemp.dat”); if(tempFile.exists()) System.exit(0); // cont.

Example: 2. Processing Data Streams // Write data try { dos = new DataOutputStream( new FileOutputStream(tempFile)); for(int i=0; i < 10; i++) dos.writeInt((int)(Math.random()*1000)); } catch (IOException ex) {... } finally { try { if(dos != null) dos.close(); } catch (IOException ex) { } }

3. Processing Data Streams try { // Read data dis = new DataInputStream(tempFile); for(int i = 0; i < 0, i++) System.out.println(dis.readInt()); } catch (FileNotFoundException ex) { System.out.println(“File not found.”) } catch (IOException ex) { System.out.println(ex.getMessage()); } finally { try { if(dis != null) dis.close(); } catch (IOException ex) { System.out.println(ex.getMessage()); } } //method }// class

Print Streams F The data output stream outputs a binary represen- tation of data, so you cannot view its contents as text. In Java, you can use print streams to output data into files. These files can be viewed as text.  The PrintStream and PrintWriter classes provide this functionality.

Buffered Streams  Java introduces buffered streams that speed up input and output by reducing the number of reads and writes. In the case of input, a bunch of data is read all at once instead of one byte at a time. In the case of output, data are first cached into a buffer, then written all together to the file. F Using buffered streams is highly recommended!

Buffered Stream Constructors F BufferedInputStream (InputStream in) // 512 bytes or // chars F BufferedInputStream (InputStream in, int bufferSize) F BufferedOutputStream (OutputStream in) F BufferedOutputStream (OutputStream in, int bufferSize) F BufferedReader(Reader in) F BufferedReader(Reader in, int bufferSize) F BufferedWriter(Writer out) F BufferedWriter(Writer out, int bufferSize)

Buffered Streams: Example BufferedReader infile = null; String inLine; try { infile = new BufferedReader(new FileReader(filename)); while((inLine = infile.readLine()) != null) { System.out.println(inLine); } } catch(FileNotFoundException ex) { System.out.println(ex.getMessage()); } catch(IOException ex) { System.out.println(ex.getMessage()); } finally() { try { if(infile != null) infile.close(); }

Text Input/Output on the Consoles F There are two types of interactive I/O. F One involves simple input from the keyboard and simple output in a pure text form. F The other involves input from various input devices and output to a graphical environment on frames and applets. F The former is referred to as text interactive I/O, and the latter is known as graphical interactive I/O.

Console Output/Input  To perform console output, you can use any of the methods for PrintStream in System.out.  However, keyboard input is not directly supported in Java. In order to get input from the keyboard, you first use the following statements to read a string from the keyboard. (cont’d)

Console Output/Input import java.io.*; public class myInput { /** Read a string from the keyboard */ public static String readString() { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // Declare and initialize the string String string = “”; // Get the string from the keyboard try { string = br.getLine(); } catch (IOException ex) { System.out.println(ex); } return string; }

Console Output/Input, cont. /** Read an int value from the keyboard */ public static int readInt() { return Integer.parseInt(readString()); } /** Read a double value from the keyboard */ public static double readDouble() { return Double.parseDouble(readString()); }... /** Read a character from the keyboard */ public static char readChar() { return readString().charAt(0); } }//class

Object Input and Output  Serializable interface F Object Streams F Example

The Serializable Interface  The Serializable interface is a marker interface. It has no methods, so you don't need to add additional code in your class that implements Serializable.  Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays.

The Object Streams  Use the ObjectOutputStream class for storing objects and the ObjectInputStream class for restoring objects.  These two classes are built upon several other classes.

Object Input/Output F import java.io.Serializable; public class MyObject implements Serializable { }... F try { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(new File(fname))); out.writeObject(myObject); out.close(); } catch(IOException e) {... }... F try { ObjectInputStream in = new ObjectInputStream( new FileInputStream(new File(fname))); myObject = (MyObject)in.readObject(); } catch(IOException e) {... }

Example: Write 2D array import java.io.*; import java.io.Serializable; public class WriteMatrix { static double[10][10] data; public static void main(String[] args) { int row = data.length; int col = data[0].length; try { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( new File(args[0]))); out.writeObject(data); out.close(); } catch(IOException e) {... } }//main }//class

Example: Read 2D array import java.io.*; public class ReadMatrix { static double[][] data; public static void main(String[] args) { try { ObjectInputStream in = new ObjectInputStream( new FileInputStream(new File(args[0]))); data = (double[][])in.readObject(); int row = data.length; int col = data[0].length; } catch(IOException e) {... } }//main }//class

Example: Write Object import java.io.*; public class WriteMyObject { MyObject obj = new MyObject(); // Object to be stored public static void main(String[] args) { try { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(new File(args[0]))); out.writeObject(obj); out.close(); } catch(IOException e) {... } }//main }//class

Example: Read Object import java.io.*; public class ReadMatrix { static MyObject obj; // Object to be restored public static void main(String[] args) { try { ObjectInputStream in = new ObjectInputStream( new FileInputStream(new File(args[0]))); obj = (MyObject)in.readObject(); } catch(IOException exc) {... } }//main }//class