SlideShare a Scribd company logo
1 of 35
Download to read offline
Sun Educational Services
Java™ Programming Language
Module 10
I/O Fundamentals
Sun Educational Services
Java™ Programming Language Module 10, slide 2 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Objectives
• Write a program that uses command-line arguments
and system properties
• Examine the Properties class
• Construct node and processing streams, and use them
appropriately
• Serialize and deserialize objects
• Distinguish readers and writers from streams, and
select appropriately between them
Sun Educational Services
Java™ Programming Language Module 10, slide 3 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Command-Line Arguments
• Any Java technology application can use
command-line arguments.
• These string arguments are placed on the command
line to launch the Java interpreter after the class name:
java TestArgs arg1 arg2 "another arg"
• Each command-line argument is placed in the args
array that is passed to the static main method:
public static void main(String[] args)
Sun Educational Services
Java™ Programming Language Module 10, slide 4 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Command-Line Arguments
1 public class TestArgs {
2 public static void main(String[] args) {
3 for ( int i = 0; i < args.length; i++ ) {
4 System.out.println("args[" + i + "] is ’" + args[i] + "’");
5 }
6 }
7 }
Example execution:
java TestArgs arg0 arg1 "another arg"
args[0] is ’arg0’
args[1] is ’arg1’
args[2] is ’another arg’
Sun Educational Services
Java™ Programming Language Module 10, slide 5 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
System Properties
• System properties are a feature that replaces the
concept of environment variables (which are
platform-specific).
• The System.getProperties method returns a
Properties object.
• The getProperty method returns a String
representing the value of the named property.
• Use the -D option on the command line to include a
new property.
Sun Educational Services
Java™ Programming Language Module 10, slide 6 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The Properties Class
• The Propertiesclass implements a mapping of names
to values (a String-to-String map).
• The propertyNames method returns an Enumeration
of all property names.
• The getProperty method returns a String
representing the value of the named property.
• You can also read and write a properties collection into
a file using load and store.
Sun Educational Services
Java™ Programming Language Module 10, slide 7 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The Properties Class
1 import java.util.Properties;
2 import java.util.Enumeration;
3
4 public class TestProperties {
5 public static void main(String[] args) {
6 Properties props = System.getProperties();
7 props.list(System.out);
8 }
9 }
Sun Educational Services
Java™ Programming Language Module 10, slide 8 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The Properties Class
The following is an example test run of this program:
java -DmyProp=theValue TestProperties
The following is the (partial) output:
java.runtime.name=Java(TM) SE Runtime Environment
sun.boot.library.path=C:jsejdk1.6.0jrebin
java.vm.version=1.6.0-b105
java.vm.vendor=Sun Microsystems Inc.
java.vm.name=Java HotSpot(TM) Client VM
file.encoding.pkg=sun.io
user.country=US
myProp=theValue
Sun Educational Services
Java™ Programming Language Module 10, slide 9 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
I/O Stream Fundamentals
• A stream is a flow of data from a source or to a sink.
• A source stream initiates the flow of data, also called an
input stream.
• A sink stream terminates the flow of data, also called an
output stream.
• Sources and sinks are both node streams.
• Types of node streams are files, memory, and pipes
between threads or processes.
Sun Educational Services
Java™ Programming Language Module 10, slide 10 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Fundamental Stream Classes
Stream Byte Streams Character Streams
Source streams InputStream Reader
Sink streams OutputStream Writer
Sun Educational Services
Java™ Programming Language Module 10, slide 11 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Data Within Streams
• Java technology supports two types of streams:
character and byte.
• Input and output of character data is handled by
readers and writers.
• Input and output of byte data is handled by input
streams and output streams:
• Normally, the term stream refers to a byte stream.
• The terms reader and writer refer to character
streams.
Sun Educational Services
Java™ Programming Language Module 10, slide 12 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The InputStream Methods
• The three basic read methods are:
int read()
int read(byte[] buffer)
int read(byte[] buffer, int offset, int length)
• Other methods include:
void close()
int available()
long skip(long n)
boolean markSupported()
void mark(int readlimit)
void reset()
Sun Educational Services
Java™ Programming Language Module 10, slide 13 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The OutputStream Methods
• The three basic write methods are:
void write(int c)
void write(byte[] buffer)
void write(byte[] buffer, int offset, int length)
• Other methods include:
void close()
void flush()
Sun Educational Services
Java™ Programming Language Module 10, slide 14 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The Reader Methods
• The three basic read methods are:
int read()
int read(char[] cbuf)
int read(char[] cbuf, int offset, int length)
• Other methods include:
void close()
boolean ready()
long skip(long n)
boolean markSupported()
void mark(int readAheadLimit)
void reset()
Sun Educational Services
Java™ Programming Language Module 10, slide 15 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The Writer Methods
• The basic write methods are:
void write(int c)
void write(char[] cbuf)
void write(char[] cbuf, int offset, int length)
void write(String string)
void write(String string, int offset, int length)
• Other methods include:
void close()
void flush()
Sun Educational Services
Java™ Programming Language Module 10, slide 16 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Node Streams
Type Character Streams Byte Streams
File
FileReader
FileWriter
FileInputStream
FileOutputStream
Memory:
array
CharArrayReader
CharArrayWriter
ByteArrayInputStream
ByteArrayOutputStream
Memory:
string
StringReader
StringWriter
N/A
Pipe
PipedReader
PipedWriter
PipedInputStream
PipedOutputStream
Sun Educational Services
Java™ Programming Language Module 10, slide 17 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
A Simple Example
This program performs a copy file operation using a manual
buffer:
java TestNodeStreams file1 file2
1 import java.io.*;
2 public class TestNodeStreams {
3 public static void main(String[] args) {
4 try {
5 FileReader input = new FileReader(args[0]);
6 try {
7 FileWriter output = new FileWriter(args[1]);
8 try {
9 char[] buffer = new char[128];
10 int charsRead;
11
12 // read the first buffer
13 charsRead = input.read(buffer);
14 while ( charsRead != -1 ) {
15 // write buffer to the output file
Sun Educational Services
Java™ Programming Language Module 10, slide 18 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
A Simple Example
16 output.write(buffer, 0, charsRead);
17
18 // read the next buffer
19 charsRead = input.read(buffer);
20 }
21
22 } finally {
23 output.close();}
24 } finally {
25 input.close();}
26 } catch (IOException e) {
27 e.printStackTrace();
28 }
29 }
30 }
Sun Educational Services
Java™ Programming Language Module 10, slide 19 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Buffered Streams
This program performs a copy file operation using a built-in
buffer:
java TestBufferedStreams file1 file2
1 import java.io.*;
2 public class TestBufferedStreams {
3 public static void main(String[] args) {
4 try {
5 FileReader input = new FileReader(args[0]);
6 BufferedReader bufInput = new BufferedReader(input);
7 try {
8 FileWriter output = new FileWriter(args[1]);
9 BufferedWriter bufOutput= new BufferedWriter(output);
10 try {
11 String line;
12 // read the first line
13 line = bufInput.readLine();
14 while ( line != null ) {
15 // write the line out to the output file
Sun Educational Services
Java™ Programming Language Module 10, slide 20 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Buffered Streams
16 bufOutput.write(line, 0, line.length());
17 bufOutput.newLine();
18 // read the next line
19 line = bufInput.readLine();
20 }
21 } finally {
22 bufOutput.close();
23 }
24 } finally {
25 bufInput.close();
26 }
27 } catch (IOException e) {
28 e.printStackTrace();
29 }
30 }
31 }
32
33
Sun Educational Services
Java™ Programming Language Module 10, slide 21 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
I/O Stream Chaining
Data Source Program
FileInputStream
BufferedInputStream
DataInputStream
Data SinkProgram
FileOutputStream
BufferedOutputStream
DataOutputStream
Input Stream Chain
Output Stream Chain
Sun Educational Services
Java™ Programming Language Module 10, slide 22 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Processing Streams
Type Character Streams Byte Streams
Buffering BufferedReader
BufferedWriter
BufferedInputStream
BufferedOutputStream
Filtering FilterReader
FilterWriter
FilterInputStream
FilterOutputStream
Converting
between bytes
and character
InputStreamReader
OutputStreamWriter
Performing
object
serialization
ObjectInputStream
ObjectOutputStream
Sun Educational Services
Java™ Programming Language Module 10, slide 23 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Processing Streams
Type Character Streams Byte Streams
Performing data
conversion
DataInputStream
DataOutputStream
Counting LineNumberReader LineNumberInputStream
Peeking ahead PushbackReader PushbackInputStream
Printing PrintWriter PrintStream
Sun Educational Services
Java™ Programming Language Module 10, slide 24 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The InputStream Class Hierarchy
InputStream
FileInputStream
ObjectInputStream
PipedInputStream
StringBufferInputStream
FilterInputStream
ByteArrayInputStream
DataInputStream
PushbackInputStream
BufferedInputStream
LineNumberInputStream
SequenceInputStream
Sun Educational Services
Java™ Programming Language Module 10, slide 25 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The OutputStream Class Hierarchy
OutputStream
FileOutputStream
ObjectOutputStream
FilterOutputStream
ByteArrayOutputStream
DataOutputStream
PrintStreamPrintStream
BufferedOutputStream
PipedOutputStream
Sun Educational Services
Java™ Programming Language Module 10, slide 26 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The ObjectInputStream and The
ObjectOutputStream Classes
• The Java API provides a standard mechanism (called object
serialization) that completely automates the process of
writing and reading objects from streams.
• When writing an object, the object input stream writes the
class name, followed by a description of the data members
of the class, in the order they appear in the stream, followed
by the values for all the fields on that object.
• When reading an object, the object output stream reads the
name of the class and the description of the class to match
against the class in memory, and it reads the values from the
stream to populate a newly allocation instance of that class.
• Persistent storage of objects can be accomplished if files (or
other persistent storage) are used as streams.
Sun Educational Services
Java™ Programming Language Module 10, slide 27 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Input Chaining Combinations: A Review
Sun Educational Services
Java™ Programming Language Module 10, slide 28 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Output Chaining Combinations: A Review
Sun Educational Services
Java™ Programming Language Module 10, slide 29 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
Serialization
• Serialization is a mechanism for saving the objects as a
sequence of bytes and rebuilding them later when
needed.
• When an object is serialized, only the fields of the object
are preserved
• When a field references an object, the fields of the
referenced object are also serialized
• Some object classes are not serializable because their
fields represent transient operating system-specific
information.
Sun Educational Services
Java™ Programming Language Module 10, slide 30 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The SerializeDate Class
1 import java.io.*;
2 import java.util.Date;
3
4 public class SerializeDate {
5
6 SerializeDate() {
7 Date d = new Date ();
8
9 try {
10 FileOutputStream f =
11 new FileOutputStream ("date.ser");
12 ObjectOutputStream s =
13 new ObjectOutputStream (f);
14 s.writeObject (d);
15 s.close ();
16 } catch (IOException e) {
17 e.printStackTrace ();
18 }
19 }
Sun Educational Services
Java™ Programming Language Module 10, slide 31 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The SerializeDate Class
20
21 public static void main (String args[]) {
22 new SerializeDate();
23 }
24 }
Sun Educational Services
Java™ Programming Language Module 10, slide 32 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The DeSerializeDate Class
1 import java.io.*;
2 import java.util.Date;
3
4 public class DeSerializeDate {
5
6 DeSerializeDate () {
7 Date d = null;
8
9 try {
10 FileInputStream f =
11 new FileInputStream ("date.ser");
12 ObjectInputStream s =
13 new ObjectInputStream (f);
14 d = (Date) s.readObject ();
15 s.close ();
16 } catch (Exception e) {
17 e.printStackTrace ();
18 }
Sun Educational Services
Java™ Programming Language Module 10, slide 33 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The DeSerializeDate Class
19
20 System.out.println(
21 "Deserialized Date object from date.ser");
22 System.out.println("Date: "+d);
23 }
24
25 public static void main (String args[]) {
26 new DeSerializeDate();
27 }
28 }
Sun Educational Services
Java™ Programming Language Module 10, slide 34 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The Reader Class Hierarchy
Reader
BufferedReader
CharArrayReader
PipedReader
FilterReader
StringReader
FileReaderInputStreamReader
LineNumberReader
PushbackReader
Sun Educational Services
Java™ Programming Language Module 10, slide 35 of 35
Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
The Writer Class Hierarchy
Writer
BufferedWriter
CharArrayWriter
PrintWriter
PipedWriter
FilterWriter
StringWriter
FileWriterOutputStreamWriter

More Related Content

What's hot

What's hot (20)

09 iec t1_s1_oo_ps_session_13
09 iec t1_s1_oo_ps_session_1309 iec t1_s1_oo_ps_session_13
09 iec t1_s1_oo_ps_session_13
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
 
Image Processing In Open Computer Vision
Image Processing In Open Computer VisionImage Processing In Open Computer Vision
Image Processing In Open Computer Vision
 
Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners
 
Java class 3
Java class 3Java class 3
Java class 3
 
Java14
Java14Java14
Java14
 
Java class 4
Java class 4Java class 4
Java class 4
 
Next Generation Java - Ceylon, Kotlin, Scala & Fantom im Überblick
Next Generation Java - Ceylon, Kotlin, Scala & Fantom im ÜberblickNext Generation Java - Ceylon, Kotlin, Scala & Fantom im Überblick
Next Generation Java - Ceylon, Kotlin, Scala & Fantom im Überblick
 
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
 
Java class 6
Java class 6Java class 6
Java class 6
 
Animate
AnimateAnimate
Animate
 
Clojure - A practical LISP for the JVM
Clojure - A practical LISP for the JVMClojure - A practical LISP for the JVM
Clojure - A practical LISP for the JVM
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
Introduction to directshow II
Introduction to directshow IIIntroduction to directshow II
Introduction to directshow II
 
Rmi
RmiRmi
Rmi
 
Dacj 1-2 a
Dacj 1-2 aDacj 1-2 a
Dacj 1-2 a
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivity
 

Viewers also liked

Applying erik erickson theory
Applying erik erickson theoryApplying erik erickson theory
Applying erik erickson theorysaxykaren
 
Educ101- Child and Adolescent Development
Educ101- Child and Adolescent DevelopmentEduc101- Child and Adolescent Development
Educ101- Child and Adolescent DevelopmentSohaimi Karon
 
10 Information Processing Part1
10 Information Processing Part110 Information Processing Part1
10 Information Processing Part1lflores
 
Sigmund frued
Sigmund fruedSigmund frued
Sigmund fruedyoufatty
 
Erickson’s Psychosocial Stages of Development
Erickson’s Psychosocial Stages of Development Erickson’s Psychosocial Stages of Development
Erickson’s Psychosocial Stages of Development sanko1sm
 
Erikson's Psychosocial Stages of Development
Erikson's Psychosocial Stages of DevelopmentErikson's Psychosocial Stages of Development
Erikson's Psychosocial Stages of Developmentsanko1sm
 
Ed102 Erickson’s theory of psychosocial development
Ed102 Erickson’s theory of psychosocial developmentEd102 Erickson’s theory of psychosocial development
Ed102 Erickson’s theory of psychosocial developmentjuljuliemer
 
Subsumption theory by_david_paul_ausubel
Subsumption theory by_david_paul_ausubelSubsumption theory by_david_paul_ausubel
Subsumption theory by_david_paul_ausubelDina Datar
 
Theories of human development an Introductory Course for Catechists
Theories of human development an Introductory Course for CatechistsTheories of human development an Introductory Course for Catechists
Theories of human development an Introductory Course for Catechistsneilmcq
 
Erik Erikson and Jean Piaget's Theory of Development
Erik Erikson and Jean Piaget's Theory of DevelopmentErik Erikson and Jean Piaget's Theory of Development
Erik Erikson and Jean Piaget's Theory of DevelopmentCecille Taragua
 
Erikson's stages (1)
Erikson's stages (1)Erikson's stages (1)
Erikson's stages (1)Smiley Rathy
 
Erick erickson, psychosocial theory
Erick erickson, psychosocial theoryErick erickson, psychosocial theory
Erick erickson, psychosocial theoryApple Vallente
 
Learning Styles of Multiple Intelligence
Learning Styles of Multiple IntelligenceLearning Styles of Multiple Intelligence
Learning Styles of Multiple IntelligenceElly Brent Baldovino
 

Viewers also liked (20)

Moral
MoralMoral
Moral
 
Erik Erikson 97
Erik Erikson 97Erik Erikson 97
Erik Erikson 97
 
Applying erik erickson theory
Applying erik erickson theoryApplying erik erickson theory
Applying erik erickson theory
 
Educ101- Child and Adolescent Development
Educ101- Child and Adolescent DevelopmentEduc101- Child and Adolescent Development
Educ101- Child and Adolescent Development
 
10 Information Processing Part1
10 Information Processing Part110 Information Processing Part1
10 Information Processing Part1
 
Sigmund frued
Sigmund fruedSigmund frued
Sigmund frued
 
Erickson’s Psychosocial Stages of Development
Erickson’s Psychosocial Stages of Development Erickson’s Psychosocial Stages of Development
Erickson’s Psychosocial Stages of Development
 
Erikson
EriksonErikson
Erikson
 
Kohlberg theory
Kohlberg theory Kohlberg theory
Kohlberg theory
 
Erikson's Psychosocial Stages of Development
Erikson's Psychosocial Stages of DevelopmentErikson's Psychosocial Stages of Development
Erikson's Psychosocial Stages of Development
 
Ed102 Erickson’s theory of psychosocial development
Ed102 Erickson’s theory of psychosocial developmentEd102 Erickson’s theory of psychosocial development
Ed102 Erickson’s theory of psychosocial development
 
Subsumption theory by_david_paul_ausubel
Subsumption theory by_david_paul_ausubelSubsumption theory by_david_paul_ausubel
Subsumption theory by_david_paul_ausubel
 
Erik erikson
Erik eriksonErik erikson
Erik erikson
 
Theories of human development an Introductory Course for Catechists
Theories of human development an Introductory Course for CatechistsTheories of human development an Introductory Course for Catechists
Theories of human development an Introductory Course for Catechists
 
Erik Erikson and Jean Piaget's Theory of Development
Erik Erikson and Jean Piaget's Theory of DevelopmentErik Erikson and Jean Piaget's Theory of Development
Erik Erikson and Jean Piaget's Theory of Development
 
Erikson's stages (1)
Erikson's stages (1)Erikson's stages (1)
Erikson's stages (1)
 
Neo Behaviorism
Neo BehaviorismNeo Behaviorism
Neo Behaviorism
 
Erick erickson, psychosocial theory
Erick erickson, psychosocial theoryErick erickson, psychosocial theory
Erick erickson, psychosocial theory
 
Module 11
Module 11Module 11
Module 11
 
Learning Styles of Multiple Intelligence
Learning Styles of Multiple IntelligenceLearning Styles of Multiple Intelligence
Learning Styles of Multiple Intelligence
 

Similar to Java I/O Fundamentals Module

4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdfamitbhachne
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)Shaharyar khan
 
Java programming concept
Java programming conceptJava programming concept
Java programming conceptSanjay Gunjal
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECSreedhar Chowdam
 
Java review00
Java review00Java review00
Java review00saryu2011
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
 
JDK 14 Lots of New Features
JDK 14 Lots of New FeaturesJDK 14 Lots of New Features
JDK 14 Lots of New FeaturesSimon Ritter
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software DevelopmentZeeshan MIrza
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals WebStackAcademy
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
20100730 phpstudy
20100730 phpstudy20100730 phpstudy
20100730 phpstudyYusuke Ando
 
Core java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutionsCore java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutionsQUONTRASOLUTIONS
 

Similar to Java I/O Fundamentals Module (20)

4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
Java Notes
Java Notes Java Notes
Java Notes
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
basic_java.ppt
basic_java.pptbasic_java.ppt
basic_java.ppt
 
Java review00
Java review00Java review00
Java review00
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Java
JavaJava
Java
 
All experiment of java
All experiment of javaAll experiment of java
All experiment of java
 
Java introduction
Java introductionJava introduction
Java introduction
 
JDK 14 Lots of New Features
JDK 14 Lots of New FeaturesJDK 14 Lots of New Features
JDK 14 Lots of New Features
 
Introduction to Java Applets
Introduction to Java AppletsIntroduction to Java Applets
Introduction to Java Applets
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
Java 8
Java 8Java 8
Java 8
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
20100730 phpstudy
20100730 phpstudy20100730 phpstudy
20100730 phpstudy
 
Core java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutionsCore java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutions
 
Introduction to java programming part 1
Introduction to java programming   part 1Introduction to java programming   part 1
Introduction to java programming part 1
 

More from Hack '

Ccna 1 examen final
Ccna 1 examen finalCcna 1 examen final
Ccna 1 examen finalHack '
 
Ccna 1 capítulo 11
Ccna 1 capítulo 11Ccna 1 capítulo 11
Ccna 1 capítulo 11Hack '
 
Ccna 1 capítulo 10
Ccna 1 capítulo 10Ccna 1 capítulo 10
Ccna 1 capítulo 10Hack '
 
Ccna 1 capitulo 09
Ccna 1 capitulo 09Ccna 1 capitulo 09
Ccna 1 capitulo 09Hack '
 
Ccna 1 capitulo 08
Ccna 1 capitulo 08Ccna 1 capitulo 08
Ccna 1 capitulo 08Hack '
 
Ccna 1 capitulo 07
Ccna 1 capitulo 07Ccna 1 capitulo 07
Ccna 1 capitulo 07Hack '
 
Ccna 1 capitulo 06
Ccna 1 capitulo 06Ccna 1 capitulo 06
Ccna 1 capitulo 06Hack '
 
Ccna 1 capitulo 05
Ccna 1 capitulo 05Ccna 1 capitulo 05
Ccna 1 capitulo 05Hack '
 
Ccna 1 capitulo 04
Ccna 1 capitulo 04Ccna 1 capitulo 04
Ccna 1 capitulo 04Hack '
 
Ccna 1 capitulo 03
Ccna 1 capitulo 03Ccna 1 capitulo 03
Ccna 1 capitulo 03Hack '
 
Ccna 1 capitulo 02
Ccna 1 capitulo 02Ccna 1 capitulo 02
Ccna 1 capitulo 02Hack '
 
Ccna1 mas el final
Ccna1 mas el finalCcna1 mas el final
Ccna1 mas el finalHack '
 
Administración y organización física de centros de computo
Administración y organización física de centros de computoAdministración y organización física de centros de computo
Administración y organización física de centros de computoHack '
 
Codigos ascii
Codigos asciiCodigos ascii
Codigos asciiHack '
 
Codigo ascii
Codigo asciiCodigo ascii
Codigo asciiHack '
 
Codigo ascii
Codigo  asciiCodigo  ascii
Codigo asciiHack '
 
Identificadores, palabras reservadas y tipos de datos [JAVA]
Identificadores, palabras reservadas y tipos de datos [JAVA]Identificadores, palabras reservadas y tipos de datos [JAVA]
Identificadores, palabras reservadas y tipos de datos [JAVA]Hack '
 
Programación orientada a objetos (POO) [JAVA]
Programación orientada a objetos (POO) [JAVA]Programación orientada a objetos (POO) [JAVA]
Programación orientada a objetos (POO) [JAVA]Hack '
 
Java morld cap2 [CURSO JAVA]
Java morld cap2 [CURSO JAVA]Java morld cap2 [CURSO JAVA]
Java morld cap2 [CURSO JAVA]Hack '
 
Hilos código [JAVA]
Hilos código [JAVA]Hilos código [JAVA]
Hilos código [JAVA]Hack '
 

More from Hack ' (20)

Ccna 1 examen final
Ccna 1 examen finalCcna 1 examen final
Ccna 1 examen final
 
Ccna 1 capítulo 11
Ccna 1 capítulo 11Ccna 1 capítulo 11
Ccna 1 capítulo 11
 
Ccna 1 capítulo 10
Ccna 1 capítulo 10Ccna 1 capítulo 10
Ccna 1 capítulo 10
 
Ccna 1 capitulo 09
Ccna 1 capitulo 09Ccna 1 capitulo 09
Ccna 1 capitulo 09
 
Ccna 1 capitulo 08
Ccna 1 capitulo 08Ccna 1 capitulo 08
Ccna 1 capitulo 08
 
Ccna 1 capitulo 07
Ccna 1 capitulo 07Ccna 1 capitulo 07
Ccna 1 capitulo 07
 
Ccna 1 capitulo 06
Ccna 1 capitulo 06Ccna 1 capitulo 06
Ccna 1 capitulo 06
 
Ccna 1 capitulo 05
Ccna 1 capitulo 05Ccna 1 capitulo 05
Ccna 1 capitulo 05
 
Ccna 1 capitulo 04
Ccna 1 capitulo 04Ccna 1 capitulo 04
Ccna 1 capitulo 04
 
Ccna 1 capitulo 03
Ccna 1 capitulo 03Ccna 1 capitulo 03
Ccna 1 capitulo 03
 
Ccna 1 capitulo 02
Ccna 1 capitulo 02Ccna 1 capitulo 02
Ccna 1 capitulo 02
 
Ccna1 mas el final
Ccna1 mas el finalCcna1 mas el final
Ccna1 mas el final
 
Administración y organización física de centros de computo
Administración y organización física de centros de computoAdministración y organización física de centros de computo
Administración y organización física de centros de computo
 
Codigos ascii
Codigos asciiCodigos ascii
Codigos ascii
 
Codigo ascii
Codigo asciiCodigo ascii
Codigo ascii
 
Codigo ascii
Codigo  asciiCodigo  ascii
Codigo ascii
 
Identificadores, palabras reservadas y tipos de datos [JAVA]
Identificadores, palabras reservadas y tipos de datos [JAVA]Identificadores, palabras reservadas y tipos de datos [JAVA]
Identificadores, palabras reservadas y tipos de datos [JAVA]
 
Programación orientada a objetos (POO) [JAVA]
Programación orientada a objetos (POO) [JAVA]Programación orientada a objetos (POO) [JAVA]
Programación orientada a objetos (POO) [JAVA]
 
Java morld cap2 [CURSO JAVA]
Java morld cap2 [CURSO JAVA]Java morld cap2 [CURSO JAVA]
Java morld cap2 [CURSO JAVA]
 
Hilos código [JAVA]
Hilos código [JAVA]Hilos código [JAVA]
Hilos código [JAVA]
 

Recently uploaded

History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 

Recently uploaded (20)

History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 

Java I/O Fundamentals Module

  • 1. Sun Educational Services Java™ Programming Language Module 10 I/O Fundamentals
  • 2. Sun Educational Services Java™ Programming Language Module 10, slide 2 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Objectives • Write a program that uses command-line arguments and system properties • Examine the Properties class • Construct node and processing streams, and use them appropriately • Serialize and deserialize objects • Distinguish readers and writers from streams, and select appropriately between them
  • 3. Sun Educational Services Java™ Programming Language Module 10, slide 3 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Command-Line Arguments • Any Java technology application can use command-line arguments. • These string arguments are placed on the command line to launch the Java interpreter after the class name: java TestArgs arg1 arg2 "another arg" • Each command-line argument is placed in the args array that is passed to the static main method: public static void main(String[] args)
  • 4. Sun Educational Services Java™ Programming Language Module 10, slide 4 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Command-Line Arguments 1 public class TestArgs { 2 public static void main(String[] args) { 3 for ( int i = 0; i < args.length; i++ ) { 4 System.out.println("args[" + i + "] is ’" + args[i] + "’"); 5 } 6 } 7 } Example execution: java TestArgs arg0 arg1 "another arg" args[0] is ’arg0’ args[1] is ’arg1’ args[2] is ’another arg’
  • 5. Sun Educational Services Java™ Programming Language Module 10, slide 5 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 System Properties • System properties are a feature that replaces the concept of environment variables (which are platform-specific). • The System.getProperties method returns a Properties object. • The getProperty method returns a String representing the value of the named property. • Use the -D option on the command line to include a new property.
  • 6. Sun Educational Services Java™ Programming Language Module 10, slide 6 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The Properties Class • The Propertiesclass implements a mapping of names to values (a String-to-String map). • The propertyNames method returns an Enumeration of all property names. • The getProperty method returns a String representing the value of the named property. • You can also read and write a properties collection into a file using load and store.
  • 7. Sun Educational Services Java™ Programming Language Module 10, slide 7 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The Properties Class 1 import java.util.Properties; 2 import java.util.Enumeration; 3 4 public class TestProperties { 5 public static void main(String[] args) { 6 Properties props = System.getProperties(); 7 props.list(System.out); 8 } 9 }
  • 8. Sun Educational Services Java™ Programming Language Module 10, slide 8 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The Properties Class The following is an example test run of this program: java -DmyProp=theValue TestProperties The following is the (partial) output: java.runtime.name=Java(TM) SE Runtime Environment sun.boot.library.path=C:jsejdk1.6.0jrebin java.vm.version=1.6.0-b105 java.vm.vendor=Sun Microsystems Inc. java.vm.name=Java HotSpot(TM) Client VM file.encoding.pkg=sun.io user.country=US myProp=theValue
  • 9. Sun Educational Services Java™ Programming Language Module 10, slide 9 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 I/O Stream Fundamentals • A stream is a flow of data from a source or to a sink. • A source stream initiates the flow of data, also called an input stream. • A sink stream terminates the flow of data, also called an output stream. • Sources and sinks are both node streams. • Types of node streams are files, memory, and pipes between threads or processes.
  • 10. Sun Educational Services Java™ Programming Language Module 10, slide 10 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Fundamental Stream Classes Stream Byte Streams Character Streams Source streams InputStream Reader Sink streams OutputStream Writer
  • 11. Sun Educational Services Java™ Programming Language Module 10, slide 11 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Data Within Streams • Java technology supports two types of streams: character and byte. • Input and output of character data is handled by readers and writers. • Input and output of byte data is handled by input streams and output streams: • Normally, the term stream refers to a byte stream. • The terms reader and writer refer to character streams.
  • 12. Sun Educational Services Java™ Programming Language Module 10, slide 12 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The InputStream Methods • The three basic read methods are: int read() int read(byte[] buffer) int read(byte[] buffer, int offset, int length) • Other methods include: void close() int available() long skip(long n) boolean markSupported() void mark(int readlimit) void reset()
  • 13. Sun Educational Services Java™ Programming Language Module 10, slide 13 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The OutputStream Methods • The three basic write methods are: void write(int c) void write(byte[] buffer) void write(byte[] buffer, int offset, int length) • Other methods include: void close() void flush()
  • 14. Sun Educational Services Java™ Programming Language Module 10, slide 14 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The Reader Methods • The three basic read methods are: int read() int read(char[] cbuf) int read(char[] cbuf, int offset, int length) • Other methods include: void close() boolean ready() long skip(long n) boolean markSupported() void mark(int readAheadLimit) void reset()
  • 15. Sun Educational Services Java™ Programming Language Module 10, slide 15 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The Writer Methods • The basic write methods are: void write(int c) void write(char[] cbuf) void write(char[] cbuf, int offset, int length) void write(String string) void write(String string, int offset, int length) • Other methods include: void close() void flush()
  • 16. Sun Educational Services Java™ Programming Language Module 10, slide 16 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Node Streams Type Character Streams Byte Streams File FileReader FileWriter FileInputStream FileOutputStream Memory: array CharArrayReader CharArrayWriter ByteArrayInputStream ByteArrayOutputStream Memory: string StringReader StringWriter N/A Pipe PipedReader PipedWriter PipedInputStream PipedOutputStream
  • 17. Sun Educational Services Java™ Programming Language Module 10, slide 17 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 A Simple Example This program performs a copy file operation using a manual buffer: java TestNodeStreams file1 file2 1 import java.io.*; 2 public class TestNodeStreams { 3 public static void main(String[] args) { 4 try { 5 FileReader input = new FileReader(args[0]); 6 try { 7 FileWriter output = new FileWriter(args[1]); 8 try { 9 char[] buffer = new char[128]; 10 int charsRead; 11 12 // read the first buffer 13 charsRead = input.read(buffer); 14 while ( charsRead != -1 ) { 15 // write buffer to the output file
  • 18. Sun Educational Services Java™ Programming Language Module 10, slide 18 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 A Simple Example 16 output.write(buffer, 0, charsRead); 17 18 // read the next buffer 19 charsRead = input.read(buffer); 20 } 21 22 } finally { 23 output.close();} 24 } finally { 25 input.close();} 26 } catch (IOException e) { 27 e.printStackTrace(); 28 } 29 } 30 }
  • 19. Sun Educational Services Java™ Programming Language Module 10, slide 19 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Buffered Streams This program performs a copy file operation using a built-in buffer: java TestBufferedStreams file1 file2 1 import java.io.*; 2 public class TestBufferedStreams { 3 public static void main(String[] args) { 4 try { 5 FileReader input = new FileReader(args[0]); 6 BufferedReader bufInput = new BufferedReader(input); 7 try { 8 FileWriter output = new FileWriter(args[1]); 9 BufferedWriter bufOutput= new BufferedWriter(output); 10 try { 11 String line; 12 // read the first line 13 line = bufInput.readLine(); 14 while ( line != null ) { 15 // write the line out to the output file
  • 20. Sun Educational Services Java™ Programming Language Module 10, slide 20 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Buffered Streams 16 bufOutput.write(line, 0, line.length()); 17 bufOutput.newLine(); 18 // read the next line 19 line = bufInput.readLine(); 20 } 21 } finally { 22 bufOutput.close(); 23 } 24 } finally { 25 bufInput.close(); 26 } 27 } catch (IOException e) { 28 e.printStackTrace(); 29 } 30 } 31 } 32 33
  • 21. Sun Educational Services Java™ Programming Language Module 10, slide 21 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 I/O Stream Chaining Data Source Program FileInputStream BufferedInputStream DataInputStream Data SinkProgram FileOutputStream BufferedOutputStream DataOutputStream Input Stream Chain Output Stream Chain
  • 22. Sun Educational Services Java™ Programming Language Module 10, slide 22 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Processing Streams Type Character Streams Byte Streams Buffering BufferedReader BufferedWriter BufferedInputStream BufferedOutputStream Filtering FilterReader FilterWriter FilterInputStream FilterOutputStream Converting between bytes and character InputStreamReader OutputStreamWriter Performing object serialization ObjectInputStream ObjectOutputStream
  • 23. Sun Educational Services Java™ Programming Language Module 10, slide 23 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Processing Streams Type Character Streams Byte Streams Performing data conversion DataInputStream DataOutputStream Counting LineNumberReader LineNumberInputStream Peeking ahead PushbackReader PushbackInputStream Printing PrintWriter PrintStream
  • 24. Sun Educational Services Java™ Programming Language Module 10, slide 24 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The InputStream Class Hierarchy InputStream FileInputStream ObjectInputStream PipedInputStream StringBufferInputStream FilterInputStream ByteArrayInputStream DataInputStream PushbackInputStream BufferedInputStream LineNumberInputStream SequenceInputStream
  • 25. Sun Educational Services Java™ Programming Language Module 10, slide 25 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The OutputStream Class Hierarchy OutputStream FileOutputStream ObjectOutputStream FilterOutputStream ByteArrayOutputStream DataOutputStream PrintStreamPrintStream BufferedOutputStream PipedOutputStream
  • 26. Sun Educational Services Java™ Programming Language Module 10, slide 26 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The ObjectInputStream and The ObjectOutputStream Classes • The Java API provides a standard mechanism (called object serialization) that completely automates the process of writing and reading objects from streams. • When writing an object, the object input stream writes the class name, followed by a description of the data members of the class, in the order they appear in the stream, followed by the values for all the fields on that object. • When reading an object, the object output stream reads the name of the class and the description of the class to match against the class in memory, and it reads the values from the stream to populate a newly allocation instance of that class. • Persistent storage of objects can be accomplished if files (or other persistent storage) are used as streams.
  • 27. Sun Educational Services Java™ Programming Language Module 10, slide 27 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Input Chaining Combinations: A Review
  • 28. Sun Educational Services Java™ Programming Language Module 10, slide 28 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Output Chaining Combinations: A Review
  • 29. Sun Educational Services Java™ Programming Language Module 10, slide 29 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 Serialization • Serialization is a mechanism for saving the objects as a sequence of bytes and rebuilding them later when needed. • When an object is serialized, only the fields of the object are preserved • When a field references an object, the fields of the referenced object are also serialized • Some object classes are not serializable because their fields represent transient operating system-specific information.
  • 30. Sun Educational Services Java™ Programming Language Module 10, slide 30 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The SerializeDate Class 1 import java.io.*; 2 import java.util.Date; 3 4 public class SerializeDate { 5 6 SerializeDate() { 7 Date d = new Date (); 8 9 try { 10 FileOutputStream f = 11 new FileOutputStream ("date.ser"); 12 ObjectOutputStream s = 13 new ObjectOutputStream (f); 14 s.writeObject (d); 15 s.close (); 16 } catch (IOException e) { 17 e.printStackTrace (); 18 } 19 }
  • 31. Sun Educational Services Java™ Programming Language Module 10, slide 31 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The SerializeDate Class 20 21 public static void main (String args[]) { 22 new SerializeDate(); 23 } 24 }
  • 32. Sun Educational Services Java™ Programming Language Module 10, slide 32 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The DeSerializeDate Class 1 import java.io.*; 2 import java.util.Date; 3 4 public class DeSerializeDate { 5 6 DeSerializeDate () { 7 Date d = null; 8 9 try { 10 FileInputStream f = 11 new FileInputStream ("date.ser"); 12 ObjectInputStream s = 13 new ObjectInputStream (f); 14 d = (Date) s.readObject (); 15 s.close (); 16 } catch (Exception e) { 17 e.printStackTrace (); 18 }
  • 33. Sun Educational Services Java™ Programming Language Module 10, slide 33 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The DeSerializeDate Class 19 20 System.out.println( 21 "Deserialized Date object from date.ser"); 22 System.out.println("Date: "+d); 23 } 24 25 public static void main (String args[]) { 26 new DeSerializeDate(); 27 } 28 }
  • 34. Sun Educational Services Java™ Programming Language Module 10, slide 34 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The Reader Class Hierarchy Reader BufferedReader CharArrayReader PipedReader FilterReader StringReader FileReaderInputStreamReader LineNumberReader PushbackReader
  • 35. Sun Educational Services Java™ Programming Language Module 10, slide 35 of 35 Copyright Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2 The Writer Class Hierarchy Writer BufferedWriter CharArrayWriter PrintWriter PipedWriter FilterWriter StringWriter FileWriterOutputStreamWriter