Download Output

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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.
1
7.0 Input-output in Java
Objective:
After completing this Topic, you will be able to handle I/O mechanism in
java
1.
2.
3.
4.
5.
6.
7.
8.
Java stream class hierarchy
File stream
Pipe stream
Stream wrapping using filters
Streams concatenation
RandomAccessFile
Serialization
Externalization
2
Stream Class Hierarchy
java.io
BufferedInputStream
ByteArrayInputStream
DataInputStream
FileInputStream
LineNumberInputStream
FilterInputStream
PushbackInputStream
PipedInputStream
InputStream
SequenceInputStream
StringBufferInputStream
ByteArrayOutputStream
Object
java.lang
OutputStream
FileOutputStream
BufferedOutputStream
FilterOutputStream
DataOutputStream
PipedOutputStream
PrintStream
3
Stream Class Hierarchy
• InputStream
– An abstract class
– All methods public
– Methods throw IOException on
error condition
Constructors
Methods
InputStream()
int read()
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()
4
Stream Class Hierarchy
• OutputStream
– An abstract class
– All methods return a void value
– Methods throw IOException on
error
Constructors
Methods
OutputStream()
void write(int b)
void write(byte b[])
void write(byte b[], int off, int len)
void flush()
void close()
5
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
6
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]);
while(in.read() != -1)
total++;
System.out.println(total +
" bytes");
}
}
Output:
12 bytes
//file: “Demo.txt” as args[0]
Hello World!
int total = 0;
continued…
7
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
catch(Exception e)
{
System.out.println("Exc
eption: " + e);
}
}
}
//file: demofile.txt
Hi, THIS IS A DEMO PROGRAM!!!
FileOutputStream("demofil
e.txt");
op.write(buf);
op.close();
}
continued…
8
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
Constructors
Methods
FileInputSream(String name)
FileInputSream(File file)
FileInputStream(FileDescriptor fdobj)
int read()
int read(byte[] buf)
int read(byte[] buf, int off, int len)
int available()
long skip(long n)
void close()
FileDescriptor getFD()
void finalize()
9
File Streams
• FileOutputStream
– Writing streams of raw bytes
– Inherits all the functionality of OutputStream
Constructors
Methods
FileOutputStream(File file)
FileOutputStream(File file, boolean append)
FileOutputStream(FileDescriptor fdobj)
FileOutputStream(String name)
FileOutputStream(String name, boolean append)
void write(int b)
void write(byte[] b)
void write(byte[] b, int off, int len)
FileDescriptor getFD()
void finalize()
void close()
10
Pipe Streams
• Used as input/output pairs
• Are thread safe
• Provide stream functionality in our code, without compelling to
build new, specialized streams
11
Pipe Streams
• PipedInputStream
– Should be connected to PipedOutputStream
– Data read from its object by one thread
– Contains a buffer
FIELDS
CONSTRUCTOR
byte[] buffer
PipedInputStream()
int in
PipedInputStream(PipedOutputSream Src)
int out
static int PIPE_SIZE
METHODS
int read()
int read(byte[] b, int off, int len)
void connect(PipedOutputSream Src)
void receive(int b)
int available()
void close()
12
Pipe Streams
• PipedOutptStream
– Can be connected to PipedInputStream to create a communications pipe
– Is the sending end of the pipe
– Used with threads
CONSTRUCTORS
METHODS
PipedOutputStream()
void write(int b)
PipedOutputStream(PipedInputStream snk) void write(byte[] b, int off, int len)
void connect(PipedInputStream snk)
void flush()
void close()
13
Pipe Streams
• Usage
PipedInputStream pin = new PipedInputStream();
PipedOutputStream pout = new PipedOutputStream( pin );
Alternatively :
PipedOutputStream pout = new PipedOutputStream( );
PipedInputStream pin = new PipedInputStream( pout );
14
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
15
Filter Streams
• 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
METHODS
InputStream 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()
16
Filter Streams
• FilterOutputStream
– Writes to the underlying streams
– Overrides all methods of OutputStream
– allows itself to be nested
FIELDS
CONSTRUCTORS
METHODS
OutputStream out
FilterOutputStream(OutputStream out) void write(byte[] b)
void write(int b)
void write(byte[] b, int off, int len)
void flush()
void close()
17
Filter Streams
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
18
Filter Streams
Output:
if (a .eq. 4) a <-- 0;
19
Streams Concatenation
• SequenceInputStream
– Concatenates multiple InputStreams logically
CONSTRUCTORS
METHODS
SequenceInputStream(Enumeration e)
int read()
SequenceInputStream(InputStream s1, InputStream s2) int read(byte[] b, int off, int len)
int available()
void close()
20
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 try
catch(IOException e){
System.out.println("Exception:
" + e);
System.exit(-1); }//end catch
}//end main }//end class
21
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
22
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
23
RandomAccessFile
import java.io.*;
class RandomAccessFileDemo
{
public static void main
(String args[]) {
try
{
RandomAccessFile rf = new
RandomAccessFile("rtest.da
t", "rw");
for(int i = 0; i < 10;
i++)
{
rf.close();
}//end try
catch (Exception e)
{
System.out.println("Error: " +
e.toString());
}//end catch
}//end main
}//end class
Output:
Data Successfully Written!!
rf.writeDouble(i*1.414);
}
System.out.println("Data
Successfully
Written!!");
continued…
24
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
25
Serialization
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 try
catch(Exception e) {
System.out.println("Exception
:" + e);
System.exit(0);
}//end catch
continued…
26
Serialization
try
{
Output
MyClass object2;
FileInputStream fis = new
FileInputStream("serial");
ObjectInputStream ois =
new ObjectInputStream(fis);
object1: s=Hello; i=-7; d=2.7E10
object2: s=Hello; i=-7; d=2.7E10
object2 =
(MyClass)ois.readObject();
ois.close();
System.out.println("object2: "
+ object2);
}//end try
catch(Exception e)
{
System.out.println("Exception
:" + e);
System.exit(0);
}//end catch
}//end main
}//end class
27
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
28
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
29
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
30
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.
31
Congratulations!
You have successfully
completed
Basic Java
Programming