Download presentation
Presentation is loading. Please wait.
Published byGervais Sparks Modified over 9 years ago
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 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.
2
2 7.0 Input-output in Java Objective: After completing this Topic, you will be able to handle I/O mechanism in java 1. Java stream class hierarchy 2. File stream 3. Pipe stream 4. Stream wrapping using filters 5. Streams concatenation 6. RandomAccessFile 7. Serialization 8. Externalization
3
3 Stream Class Hierarchy
4
4 InputStream –An abstract class –All methods public –Methods throw IOException on error condition
5
5 Stream Class Hierarchy OutputStream –An abstract class –All methods return a void value –Methods throw IOException on error
6
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
7
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]file Hello World!
8
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("demofil e.txt"); op.write(buf); op.close(); } continued… catch(Exception e) { System.out.println("Exc eption: " + e); } //file: demofile.txt Hi, THIS IS A DEMO PROGRAM!!!
9
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
10
10 File Streams FileOutputStream –Writing streams of raw bytes –Inherits all the functionality of OutputStream
11
11 Pipe Streams Used as input/output pairs Are thread safe Provide stream functionality in our code, without compelling to build new, specialized streams
12
12 Pipe Streams PipedInputStream –Should be connected to PipedOutputStream –Data read from its object by one thread –Contains a buffer
13
13 Pipe Streams PipedOutptStream –Can be connected to PipedInputStream to create a communications pipe –Is the sending end of the pipe –Used with threads
14
14 Usage PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream( pin ); Alternatively : PipedOutputStream pout = new PipedOutputStream( ); PipedInputStream pin = new PipedInputStream( pout ); Pipe Streams
15
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
16
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))); Filter Streams
17
17 FilterOutputStream –Writes to the underlying streams –Overrides all methods of OutputStream – allows itself to be nested Filter Streams
18
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
19
19 Output: if (a.eq. 4) a <-- 0; Filter Streams
20
20 Streams Concatenation SequenceInputStream –Concatenates multiple InputStreams logically
21
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 try catch(IOException e){ System.out.println("Exception: " + e); System.exit(-1); }//end catch }//end main }//end class
22
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
23
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
24
24 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.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!!
25
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
26
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 try catch(Exception e) { System.out.println("Exception :" + e); System.exit(0); }//end catch continued… Serialization
27
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 try catch(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
28
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
29
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
30
30 Basic Java Programming: Next Step The following items will provide more information on the subjects covered in this course: Resource Type DescriptionReference Topic or Module BookA programmers guide to Java certification – Khalid Mughal & Rolf W. Rasmussen Module 2, Module 3, Module 4, Module 6 BookThinking in Java – Bruce EckelModule 1, Module 2, Module 4 BookThe Java programming language second edition- Ken Arnold & James Gosling Module 3, Module 4, Module 5, Module 7 BookJava complete reference – Herbert Shield Module 2, Module 3, Module 5, Module 7 URLhttp://java.sun.comModule 2, Module 7
31
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.
32
Congratulations! You have successfully completed Basic Java Programming
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.