Input and Output  Stream Classes Processing External Files Data Streams Print Streams Buffered Streams Text Input and Output on the Console  Object Streams     

Download Report

Transcript Input and Output  Stream Classes Processing External Files Data Streams Print Streams Buffered Streams Text Input and Output on the Console  Object Streams     

Input and Output

 Stream Classes  Processing External Files  Data Streams  Print Streams  Buffered Streams  Text Input and Output on the Console  Object Streams

Streams

 A

stream

is an abstraction of the continuous one-way flow of data. Input Stream Program File Output Stream

Stream Classes

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

 In all, over 40 classes are used to provide input and output.

Object

A) Byte Stream Classes

InputStream

ByteArrayInputStream

FileInputStream

FilterInputStream SequenceInputStream PipedInputStream

ObjectInputStream

StringBufferInputStream

DataInputStream

BufferedInputStream LineNumberInputStream PushBackInputStream

ObjectInput

OutputStream

ByteArrayOutputStream

FileOutputStream

FilterOutputStream PipedOutputStream

ObjectOutputStream

BufferedOutputStream

DataOutputStream PrintStream

ObjectOutput DataOutput DataInput

RandomAccessFile

B) Character Stream Classes

Object

Reader

Writer CharArrayReader InputStreamReader FilterReader StringReader PipedReader

BufferedReader

BufferedWriter CharArrayWriter OutputStreamWriter FilterWriter PipedWriter

PrintWriter

StringWriter

FileReader

PushBackReader LineNumberReader

FileWriter StreamTokenizer

Abstract InputStream Class

abstract int read() throws IOException

read the next byte and returns its value, an int in range 0 255; at the end returns -1.

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

int available() throws IOException

Returns the number of bytes that can be read form the input stream. 

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.

abstract int read() throws IOException

int read(char b[]) throws IOException

void close() throws IOException

void skip(long n) throws IOException

Abstract OutputStream Class

abstract void write(int b) throws IOException

void write(byte[] b) throws IOException

void close() throws IOException

void flush() throws IOException

Abstract Writer Class

abstract void write(char b) throws IOException

void write(char[] b) throws IOException

void close() throws IOException

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”); 

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

FileInputStream fis program args[0] args[1] FileOutputStream fos

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  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.  Data streams are

wrappers

for on existing input and output streams: DataInputStream dis = new DataInputStream(inStream);

DataInputStream Methods

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

DataOutputStream Methods

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

Example: Using Data Streams

DataInputStream dis program DataOutputStream dos FileInputStream FileOutputStream mytemp.dat

mytemp.dat

Data I/O Stream Constructors

 DataInputStream in = new DataInputStream(inpStream); DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); Creates a data input stream for file in.dat.

 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

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

Using buffered streams is highly recommended!

Buffered Stream Constructors

 BufferedInputStream (InputStream in) // 512 bytes or // chars  BufferedInputStream (InputStream in, int bufferSize)  BufferedOutputStream (OutputStream in)  BufferedOutputStream (OutputStream in, int bufferSize)  BufferedReader(Reader in)  BufferedReader(Reader in, int bufferSize)  BufferedWriter(Writer out)  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

 There are two types of interactive I/O.  One involves simple input from the keyboard and simple output in a pure text form.  The other involves input from various input devices and output to a graphical environment on frames and applets.  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

Object Streams

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

 public class MyObject implements Serializable { } . . .

 import java.io.Serializable; try { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(new File(fname))); out.writeObject(myObject); out.close(); } catch(IOException e) { ... } . . .

 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