1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to...

32
1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of input or output of data. Its quite challenging since not only are there different kinds of IO that you want to communicate with(files, the console, network connections), but you need to talk to them in a wide variety of ways(sequential, binary, random-access, character, by lines, by words, etc.). This module is going to introduce you with the various classes available with the java.io package that overcomes the challenge of handling i/o in a variety of ways and in different formats.

Transcript of 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to...

Page 1: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

1

7.0 Input-output in Java : Overview

Introduction:

It would be quite impossible for any program to do anything useful without performing some kind of input or output of data. Its quite challenging since not only are there different kinds of IO that you want to communicate with(files, the console, network connections), but you need to talk to them in a wide variety of ways(sequential, binary, random-access, character, by lines, by words, etc.).

This module is going to introduce you with the various classes available with the java.io package that overcomes the challenge of handling i/o in a variety of ways and in different formats.

Page 2: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

2

7.0 Input-output in Java

Objective:

After completing this Topic, you will be able to handle I/O mechanism in java1. Java stream class hierarchy

2. File stream

3. Pipe stream

4. Stream wrapping using filters

5. Streams concatenation

6. RandomAccessFile

7. Serialization

8. Externalization

Page 3: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

3

Stream Class Hierarchy

java.lang

Object

InputStream

OutputStream

FileInputStream

FilterInputStream

PipedInputStream

SequenceInputStream

StringBufferInputStream

FileOutputStream

FilterOutputStream

PipedOutputStream

ByteArrayInputStream

BufferedInputStream

DataInputStream

LineNumberInputStream

PushbackInputStream

DataOutputStream

BufferedOutputStream

PrintStream

ByteArrayOutputStream

java.io

Page 4: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

4

Stream Class Hierarchy

• InputStream– An abstract class

– All methods public

– Methods throw IOException on error condition

Constructors Methods

int read(byte[] buf)int read(byte[] buf, int off, int len)int available()long skip(long n)void close()void mark(int readlimit)void reset()

InputStream() int read()

Page 5: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

5

Stream Class Hierarchy

• OutputStream– An abstract class

– All methods return a void value

– Methods throw IOException on error

Methodsvoid write(int b)

void write(byte b[])

void write(byte b[], int off, int len)

void flush()

void close()

ConstructorsOutputStream()

Page 6: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

6

Stream Class Hierarchy

• Predefined Streams– System in the java.lang package

– Contains three predefined stream variables – in, out and err

– System.out

• standard out stream

• Object of type PrintStream

– System.in

• standard input

• Of type InputStream

– System.err

• standard error stream

• Object of type PrintStream

Page 7: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

7

Stream Class Hierarchy

import java.io.*;class InputStreamDemo{ public static void

main(String[] args) throws IOException

{InputStream in;if(args.length == 0) in = System.in;else

in = new FileInputStream(args[0]);

int total = 0; continued…

while(in.read() != -1)

total++;

System.out.println(total + " bytes");

}

}

Output:

12 bytes

//file: “Demo.txt” as args[0]

Hello World!

Page 8: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

8

Stream Class Hierarchy

import java.io.*;class OutputStreamDemo{ public static void main(String

args[]) {

String str = "Hi, THIS IS A DEMO PROGRAM!!!";byte buf[] = str.getBytes();try{

OutputStream op = new

FileOutputStream("demofile.txt");

op.write(buf);op.close();

} continued…

catch(Exception e)

{

System.out.println("Exception: " + e);

}

}

}

//file: demofile.txt

Hi, THIS IS A DEMO PROGRAM!!!

Page 9: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

9

File Streams

• Treats file as a stream of input or output• FileInputStream

– Inherits all standard InputStream functionality

– provides only a low-level interface to reading data

MethodsFileInputSream(String name) int read()FileInputSream(File file) int read(byte[] buf)FileInputStream(FileDescriptor fdobj) int read(byte[] buf, int off, int len)

int available()long skip(long n)void close()FileDescriptor getFD()void finalize()

Constructors

Page 10: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

10

File Streams

• FileOutputStream– Writing streams of raw bytes

– Inherits all the functionality of OutputStream

Constructors MethodsFileOutputStream(File file) void write(int b)FileOutputStream(File file, boolean append) void write(byte[] b)FileOutputStream(FileDescriptor fdobj) void write(byte[] b, int off, int len)FileOutputStream(String name) FileDescriptor getFD()FileOutputStream(String name, boolean append) void finalize()

void close()

Page 11: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

11

Pipe Streams

• Used as input/output pairs• Are thread safe• Provide stream functionality in our code, without compelling to

build new, specialized streams

Page 12: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

12

Pipe Streams

• PipedInputStream– Should be connected to PipedOutputStream

– Data read from its object by one thread

– Contains a buffer

FIELDS CONSTRUCTOR METHODSbyte[] buffer PipedInputStream() int read()

int in PipedInputStream(PipedOutputSream Src) int read(byte[] b, int off, int len)int out void connect(PipedOutputSream Src)static int PIPE_SIZE void receive(int b)

int available()

void close()

Page 13: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

13

Pipe Streams

• PipedOutptStream– Can be connected to PipedInputStream to create a communications pipe

– Is the sending end of the pipe

– Used with threads

CONSTRUCTORS METHODSPipedOutputStream() void write(int b)

PipedOutputStream(PipedInputStream snk) void write(byte[] b, int off, int len)void connect(PipedInputStream snk)void flush()

void close()

Page 14: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

14

• Usage

PipedInputStream pin = new PipedInputStream();

PipedOutputStream pout = new PipedOutputStream( pin );

Alternatively :

PipedOutputStream pout = new PipedOutputStream( );

PipedInputStream pin = new PipedInputStream( pout );

Pipe Streams

Page 15: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

15

Filter Streams

• Wrappers around underlying input or output streams• Chain streams to produce composite streams of greater power• Extensions are buffering, character translation and raw data

translation• Typically accessed by methods expecting a generic stream

Page 16: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

16

• FilterInputStream– Contains other streams as basic source of data

– Overrides all methods of InputStream

– Allows itself to be nested

e.g.

InputStream s = new FileInputStream();

FilterInputStream s3 = new FilterInputStream(new FilterInputStream(new FilterInputStream(s)));

FIELDS CONSTRUCTORS METHODSInputStream in FilterInputStream(InputStream in) int read()

int read(byte[] b)

int read(byte[] b, int off, int len)

long skip(long n)

int available()

void mark(int readlimit)

void reset()

void close()

Filter Streams

Page 17: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

17

• FilterOutputStream– Writes to the underlying streams

– Overrides all methods of OutputStream

– allows itself to be nested

FIELDS CONSTRUCTORS METHODSOutputStream out FilterOutputStream(OutputStream out) void write(byte[] b)

void write(int b)

void write(byte[] b, int off, int len)

void flush()

void close()

Filter Streams

Page 18: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

18

import java.io.*;

class PushbackInputStreamDemo

{

public static void main(String args[]) throws IOException

{

String s = "if (a == 4) a = 0;";

byte buf[] = s.getBytes();

ByteArrayInputStream in = new

ByteArrayInputStream(buf);

PushbackInputStream f = new

PushbackInputStream(in);

int c;

continued…

while((c = f.read()) != -1)

{

switch(c){

case '=':

if((c = f.read()) == '=')

System.out.print(".eq.");

else

{

System.out.print("<--");

f.unread(c);

}

break;

default:

System.out.print((char)c);

break;

}//end switch

}//end while

}//end main

}//end class

Filter Streams

Page 19: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

19

Output:

if (a .eq. 4) a <-- 0;

Filter Streams

Page 20: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

20

Streams Concatenation

• SequenceInputStream– Concatenates multiple InputStreams logically

CONSTRUCTORS METHODSSequenceInputStream(Enumeration e) int read()

SequenceInputStream(InputStream s1, InputStream s2) int read(byte[] b, int off, int len)

int available()

void close()

Page 21: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

21

Streams Concatenation

import java.io.*;

import java.util.Vector;

import java.util.Enumeration;

class StreamConcat

{

public static void main(String args[])

{

try

{

InputStream in;

if(args.length == 0)

{

in = System.in;

}

else

{

InputStream filein, bufin;

continued…

Vector inputs = new Vector(args.length);

for(int i=0;i<args.length;i++) {

filein = new FileInputStream(args[i]);

bufin = new BufferedInputStream(filein);

inputs.addElement(bufin); }

Enumeration files = inputs.elements();

in = new SequenceInputStream(files); }

int ch;while((ch = in.read()) != -1)

System.out.write(ch);}//end trycatch(IOException e){

System.out.println("Exception: " + e);System.exit(-1); }//end catch

}//end main }//end class

Page 22: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

22

Streams Concatenation

Output:

C:\jdk1.3\bin>java StreamConcat rtest.txt Demo.txt

Hi here's some data from rtest.txt

Hi I am from Demo.txt

Page 23: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

23

RandomAccessFile

• “Random access” – supports positioning request• Encapsulates a random access file• Not derived from InputStream or OutputStream• Implements DataInput and DataOutput interfaces• Cannot be used where other input/output streams required• DataInput interface

– Reading data from a binary stream and reconstructing into primitive types

• DataOutput interface– Converting data of primitive types to bytes and writing to binary streams

Page 24: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

24

RandomAccessFile

import java.io.*;class RandomAccessFileDemo{ public static void main

(String args[]) {try{

RandomAccessFile rf = new RandomAccessFile("rtest.dat", "rw");

for(int i = 0; i < 10; i++)

{

rf.writeDouble(i*1.414);}

System.out.println("Data Successfully Written!!"); continued…

rf.close();

}//end try

catch (Exception e)

{System.out.println("Error:

" + e.toString());

}//end catch

}//end main

}//end class

Output:

Data Successfully Written!!

Page 25: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

25

Serialization

• Writing state of an object to a byte stream or to a persistent storage area

• Needed to implement Remote Method Invocation (RMI)• Data declared as transient not saved during serialization• Static variables are also not saved• Classes that support Serialization

– ObjectInputStream

– ObjectOutputStream

• Interfaces that support Serialization– Serializable

– Externalizable

– ObjectInput

– ObjectOutput

Page 26: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

26

import java.io.*;class MyClass implements

Serializable { String s; int i; double d; public MyClass(String s, int i,

double d) {this.s = s;this.i = i;this.d = d;

} public String toString() {

return "s=" + s + "; i=" + i + "; d=" + d;

}}//end class continued…

public class SerializationDemo { public static void main(String

args[]) {try {

MyClass object1 = new MyClass("Hello",-7,2.7e10);

System.out.println("object1: " + object1);

FileOutputStream fos = new FileOutputStream("serial");

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(object1);oos.flush();oos.close();

}//end trycatch(Exception e) {

System.out.println("Exception :" + e);

System.exit(0);}//end catch continued…

Serialization

Page 27: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

27

Serialization

try{

MyClass object2;FileInputStream fis = new

FileInputStream("serial");ObjectInputStream ois =

new ObjectInputStream(fis);object2 =

(MyClass)ois.readObject();ois.close();System.out.println("object2:

" + object2);}//end trycatch(Exception e)

{

System.out.println("Exception :" + e);

System.exit(0);}//end catch

}//end main}//end class

Output

object1: s=Hello; i=-7; d=2.7E10

object2: s=Hello; i=-7; d=2.7E10

Page 28: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

28

Externalization

• Is an interface that says “Object responsible for its own state”• Is less safe as compared to serialization• Does not maintain any notion of class and identity• Package structure:

package java.io;

public interface Externalizable extends Serializable {

public void writeExternal(ObjectOutput out) throws IOException;

public void readExternal(ObjectInput in) throws IOException,

java.lang.ClassNotFoundException;

}

• Following holds for a Externalizable class:– Must implement java.io.Externalizable.

– Must implement writeExternal to save the state of an object

– Must implement readExternal to restore the state of an object

Page 29: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

29

Input-output in Java : Summary

• The Various Input Streams are:– FileInputStream– ByteArrayInputStream– FilterInputStream– PipedInputStream– StringBufferInputStream– SequenceInputStream

• The Various Output Streams are:– ByteArrayOutputStream– FileOutputStream– FilterInputStream– PipedOutputStream

• Various Filter Input and Output Streams are used depending on for what functionality they are required

• RandomAccessFile allows to read and write to file any desired position • Serialization allows to store the state of an object or of a program to

persistent storage and also used in RMI• Externalizable gives complete, explicit control of serialization process

Page 30: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

30

Basic Java Programming: Next Step

The following items will provide more information on the subjects covered in this course:

Resource Type

Description Reference Topic or Module

Book A programmers guide to Java certification – Khalid Mughal & Rolf W. Rasmussen

Module 2, Module 3, Module 4, Module 6

Book Thinking in Java – Bruce Eckel Module 1, Module 2, Module 4

Book The Java programming language second edition- Ken Arnold & James Gosling

Module 3, Module 4 , Module 5 , Module 7

Book Java complete reference – Herbert Shield

Module 2, Module 3, Module 5, Module 7

URL http://java.sun.com Module 2, Module 7

Page 31: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

31

Basic Java Programming - Summary

• It is simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, multithreaded, and dynamic.

• The JVM, is an abstract computer that runs compiled Java programs.• Widening conversion doesn’t require casting, narrowing conversion does require• Packages encapsulate related classes, interfaces and sub-packages • Java follows single inheritance model.• An interface is an expression of pure design whereas a class is a mix of design and

implementation.• Exception signals the occurrence of unexpected condition during execution.• Assertions are used to validate assumptions about the state of the program at specified

locations in the code.• The garbage collector attempts to remove objects from memory when they are not used. • Java provides built-in support for multithreaded programming.• Object class is the super class of all java classes and contains many basic methods that

are implemented by all other classes.• A collection is an object that contains other objects and provides methods for working on

the objects it contains. • Serialization allows to store the state of an object or of a program to persistent storage.

Page 32: 1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.

Congratulations!Congratulations!You have successfully You have successfully

completedcompleted

Congratulations!Congratulations!You have successfully You have successfully

completedcompleted

Basic Java Basic Java ProgrammingProgramming