100% found this document useful (1 vote)
328 views44 pages

Chapter 4 Streams and File IO

This document provides an overview of a 3 credit hour Java Programming course that meets for 2 lecture hours, 3 lab hours, and 2 tutorial hours per week. The course covers topics related to streams and file input/output in Java, including various stream classes, using streams, object streams, and file management. Specific topics discussed include input/output streams, byte streams, character streams, using streams for I/O, object streams, and outputting results to the screen.

Uploaded by

Galatom Yadeta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
328 views44 pages

Chapter 4 Streams and File IO

This document provides an overview of a 3 credit hour Java Programming course that meets for 2 lecture hours, 3 lab hours, and 2 tutorial hours per week. The course covers topics related to streams and file input/output in Java, including various stream classes, using streams, object streams, and file management. Specific topics discussed include input/output streams, byte streams, character streams, using streams for I/O, object streams, and outputting results to the screen.

Uploaded by

Galatom Yadeta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Course Title: Java Programming.

Credit Hour: 3 hrs.


ECTS: 5 [2 Lecture , 3 Lab and 2 Tutorial Hours]
Lecture Schedule: Every _____________

Bedasa Wayessa

Java Programming CoSc3053 1


Chapter 4
Streams and File I/O

Java Programming CoSc3053 2


Chapter Outline
 Input output streams
– Various stream classes
– Using Streams
– Object Streams
 File management

Java Programming CoSc3053 3


Streams
 Java I/O stream is the flow of data that you can either read from, or
you can write to.
 It is used to perform read and write operations in file permanently.
 A stream is a sequence of bits of information that is passed along a
virtual path between a source and a destination.
 An Input Stream provides a path from a source to a program.
 An Output Stream is a path from a program to a destination.
 Sources and destinations of information can be
– files, disks and networked resources.
 Java uses streams to perform these tasks.
 Java I/O stream is also called File Handling, or File I/O.

Java Programming CoSc3053 4


Streams
 Java.io package provides classes for system input and output through files,
network streams, memory buffers, etc.

 Some input-output stream will be initialized automatically by the JVM and these
streams are available in System class as in, out, and err variable.
– In reference refers to the default input device, i.e. keyboard.
– Out and err refers to the default output device, i.e. console.
Java Programming CoSc3053 5
Streams
 Streams are the sequence of bits(data).
 There are two types of streams:
1. Input Streams
 Used to read the data from various input devices like
keyboard, file, network, etc.
 That provides input to a program
 System.in is an input stream
2. Output Streams
 used to write the data to various output devices like monitor,
file, network, etc.
 That accepts output from a program
 System.out is an output stream
Java Programming CoSc3053 6
Streams
 Streams based on data
 There are two types of streams based on data:
1. Byte Stream: used to read or write byte data.
2. Character Stream: used to read or write character data.
 Reading from an Input Stream

 Writing to an Output Stream

Java Programming CoSc3053 7


Streams
1. Byte Input Stream:
 These are used to read byte data from various input devices.
 InputStream is an abstract class and it is the super class of all the
input byte streams.
 List of Byte Input Streams:
 FileInputStream
 FilterInputStream
 DataInputStream
 BufferedInputStream
 ObjectInputStream
 ByteArrayInputStream

Java Programming CoSc3053 8


Streams
1. Byte Output Stream:
 These are used to write byte data to various output devices.
 OutputStream is an abstract class and it is the superclass for all
the output byte streams.
 List of Byte Output Streams:
 FileOutputStream
 FilterOutputStream
 DataOutputStream
 BufferedOutputStream
 ObjectOutputStream
 ByteArrayOutputStream

Java Programming CoSc3053 9


Streams
 Byte Input and Output Stream:

InputStream, OutputStream, and their subclasses are for


performing binary I/O.
Java Programming CoSc3053 10
Streams
 Byte Input and Output Stream:

• The abstract InputStream class • The abstract OutputStream

defines the methods for the input class defines the methods for the

stream of bytes. output stream of bytes.


Java Programming CoSc3053 11
Byte Streams…
 Example
public class InputOutput {
public static void main(String[] args) throws IOException
{
FileInputStream fis = null;
int n=0;
try {
fis= new FileInputStream("c:\\exmpl.txt");
while((n=fis.read())!=-1) {
System.out.print((char)n);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
fis.close();
}catch(Exception e) {
System.out.println(e);
}
}

Java Programming CoSc3053 12


Streams
2. Character Input Stream:
– These are used to read char data from various input devices.
– Reader is an abstract class and is the super class for all the
character input streams.
– List of Character Reader Streams:
• CharArrayReader
• BufferedReader
• FilterReader
– FileReader
• InputStreamReader
• StringReader
Java Programming CoSc3053 13
Streams
2. Character Output Stream:
– These are used to write char data to various output devices.
– Writer is an abstract class and is the super class of all the
character output streams.
– List of Character Writer Streams:
• CharArrayWriter
• BufferedWriter
• PrintWriter
• OutputStreamReader
– FileWriter
• FilterWriter
Java Programming CoSc3053 14
Streams…
 Example: Character Stream
public class ReadFileDemo {

public static void main(String[] args) {

BufferedReader br = null;
BufferedReader br2 = null;

try{
br = new BufferedReader(new FileReader(“B:\\myfile.txt”));
String contentLine = br.readLine();
while (contentLine != null) {
System.out.println(contentLine);
contentLine = br.readLine();}
}

catch (IOException ioe) {


ioe.printStackTrace();
}
}
}

Java Programming CoSc3053 15


Using Streams
 A general algorithm for using streams for I/O in an application can be
expressed as follows:
1. Instantiate a stream object: this automatically opens the stream.
2. Read from or write to the stream in a try block.
3. Catch IOException objects (and any other exceptions that may
occur).
4. Close the stream.

Java Programming CoSc3053 16


Object Streams
 Object streams are typically used in an application when live
objects are required to be written to a byte stream and either saved
to a local file or transferred across a network to a remote host.
 An ObjectOutputStream and ObjectInputStream object writes
to a stream and read from the stream.
 The process of translating an object into a stream of bytes is known
as serialization.
 The reverse process of reconstituting an object from an input stream
is known as deserialization.
 The term ‘serialization’ is usually used to describe the overall process
of serialization and deserialization.
Java Programming CoSc3053 17
Object Streams…
 The following example shows the usage
of java.io.ObjectInputStream.readObject() method.

public static void main(String[] args) {

String s = "Hello World";

byte[] b = {'e', 'x', 'a', 'm', 'p', 'l', 'e'};


try {
// create a new file with an ObjectOutputStream
FileOutputStream out =new FileOutputStream(“E:\\test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);

// write something in the file


oout.writeObject(s);
oout.writeObject(b);
oout.flush();

// create an ObjectInputStream for the file we created before


ObjectInputStream ois = new ObjectInputStream(new
FileInputStream(“E:\\test.txt"));
Java Programming CoSc3053 18
Object Streams…
// read and print an object and cast it as string
System.out.println(""+ (String) ois.readObject());

// read and print an object and cast it as string


byte[] read = (byte[]) ois.readObject();

String s2 = new String(read);


System.out.println("" + s2);

}
catch (Exception ex) {
ex.printStackTrace();
}
}

When you compile and run the above program, it will produce
the following result:
Hello World
example

Java Programming CoSc3053 19


Screen Output
 To output the results of test classes to a computer’s screen we use
the statement
System.out.println( <parameter> );
 The System class includes a number of fields that are used for input
and output.
 The static field with the identifier out provides an output stream of
the PrintStream type.
 The stream is automatically open and is ready to accept output data.
 The class PrintStream inherits from a subclass of OutputStream.

Java Programming CoSc3053 20


Screen Output…
 A PrintStream object adds functionality to its parent output stream,
so that it can print primitive data to the console.
 All characters printed by a PrintSteam object are converted into
bytes using the platform's default character encoding.
 One interesting and convenient feature of PrintStream objects is
that they never throw an IOException.

Java Programming CoSc3053 21


Standard Streams
 All the programming languages provide support for standard I/O
– where user's program can take input from a keyboard and
– then produce output on the computer screen.
 If you are aware if C or C++ programming languages, then you must be
aware of three standard devices STDIN, STDOUT and STDERR.
 Similar way Java provides following three standard streams
– Standard Input:
• System.in
– Standard Output:
• System.out
– Standard Error:
• System.err
Java Programming CoSc3053 22
Standard Streams
 Similar way Java provides following three standard streams
– Standard Input:
• This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as
System.in.
– Standard Output:
• This is used to output the data produced by the user's program and
usually a computer screen is used to standard output stream and
represented as System.out.
– Standard Error:
• This is used to output the error data produced by the user's
program and usually a computer screen is used to standard error
stream and represented as System.err.
Java Programming CoSc3053 23
Standard Streams
 Following is a simple program which creates InputStreamReader to read standard
input stream until the user types a "q":
import java.io.*;
public class ReadConsole {
public static void main(String args[]) throws IOException {
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
}while(c != 'q’);
}finally {
if(cin != null) {
cin.close();
}
}
}
}

Java Programming CoSc3053 24


Screen Output…
 Standalone Java applications, such as those that use a dedicated main
method for testing purposes, write a line of output as follows:
System.out.println( data );
 The print and println methods of the PrintStream class are overloaded for
primitive data types.
 If an object reference is passed to any of the variants of print or println, as in
System.out.println( objectReference );
 The println method calls String.valueOf ( objectReference) to
return the object’s String value.
 Invoking toString on an object reference returns what is known as the
String representation of the object.

Java Programming CoSc3053 25


Keyboard Input
 The static field with the identifier in of the System class is an
InputStream object that can be used for keyboard input.
 Given that InputStream is an abstract class, an appropriate subclass is
automatically instantiated when accessing the in field of System.
 This stream is already open and ready to supply input data.
 The InputStream class has a read method that reads a byte of data
and returns an int in the range 0 to 255.
 The int is cast to convert it to a char.
 The following example shows how a byte is entered via the
computer’s keyboard and output to the computer’s screen.

Java Programming CoSc3053 26


Keyboard Input…
 Example:
public static void main( String[ ] args ) {
try{
System.out.print( "Please press any key: " );
char key = ( char )System.in.read( );
System.out.print( "The key pressed was: " + key );
System.out.println( "The class is: " + System.in.toString( ) );
}catch( IOException ioe ){
// do something about the exception
}
} // end of main

Output will be: Please press any key: a


The key pressed was: a
The class is: java.io.BufferedInputStream@3e25a5

Java Programming CoSc3053 27


Keyboard Input…
 The output shows that selecting System.in. toString( ) returns the object
reference of the object that is automatically instantiated when referring to
System.in and shows that the object is of the type
BufferedInputStream.
 We can conclude, therefore, that selecting System.in instantiates an object of
the BufferedInputStream type and closes the stream when it has been
finished with.
 Using System.in.read is not a particularly useful way to input data from the
computer’s keyboard.
 As an alternative, a number of streams can be chained together in order to
read characters and strings and numbers from the keyboard.

Java Programming CoSc3053 28


Keyboard Input…
 String Input via the Keyboard
– The following class chains three streams in order to read characters from
the keyboard.
– Firstly, System. In is the byte stream that is used for keyboard input.
– Secondly, System. in is connected to a stream of the InputStreamReader
type to act as a bridge between the byte stream and a character stream.
– Thirdly, a buffer is required because keyboard input tends to be irregular.
– Therefore, the InputStreamReader is connected to a buffer of the
BufferedReader type.
– The readLine method of BufferedReader reads, in the example below, a set
of characters from the keyboard.
– When the enter key is pressed, the method returns a String.
– Chaining the three streams together is achieved by passing one stream
object to the constructor of the next stream in the chain.

Java Programming CoSc3053 29


Keyboard Input…
 Example:
import java.io.*;
public class KeyboardInput {
public static void main( String[ ] args ) {

// Instantiate a bridge stream and pass the object instantiated by


//System.in to its constructor.

InputStreamReader isr = new InputStreamReader( System.in );


// Instantiate a buffered stream and pass the I nputSt reamReader to its
//constructor.

BufferedReader kbd = new BufferedReader( isr );


try{
System.out.print( "Enter some characters and press return when finished: " );
Java Programming CoSc3053 30
Keyboard Input…
String s = kbd.readLine( );
System.out.println( "The String was: " + s );

// Close the initial stream; this will close all streams connected to it.
kbd.close( );
}catch( IOException e ){
e.printStackTrace( );}
} // end of main
} // end of class definition
The result of executing main is:
Enter some characters and press return when finished: Hello World
The String was: Hello World

Java Programming CoSc3053 31


Keyboard Input…
 Numerical Input via the Keyboard
import java.io.*;
public class ReadInt {
public static void main( String[ ] args ) {
try{
BufferedReader kbd = new BufferedReader( new InputStreamReader(
System.in ) );
System.out.print( "Enter an integer: " );
String intStr = kbd.readLine( );
// Convert the String into its corresponding integer by calling one
// of the methods of the Integer wrapper class.
int number = Integer.parseInt( intStr );
System.out.println( "The number is " + number );

Java Programming CoSc3053 32


Keyboard Input…
} catch( IOException ioe ) {
// do something about it
}
} //End of main.
} // End of class definition.

The result of executing main is as follows:


Enter an integer: 123
The number is 123
The class definition shown on the next page shows a similar way to enter a double
into a program from the keyboard.

Java Programming CoSc3053 33


Files and File I /O
 File objects and file streams are useful when an application needs to
write data to a file and read data from a file, where the file (or files)
are used for persistent data associated with the application.
 The activities associated with files and file I/O involves the following
tasks:-
– Creating file objects;
– Using utilities for file objects;
– Reading and writing with file streams.

Java Programming CoSc3053 34


Creating File Objects
 An instance of the File class is an abstract representation of the path name of
a file and may or may not represent an existing file.
 For example, the following class definition compiles whether the file exists or
not.
import java.io.File;
public class Files {
public static void main( String[ ] args ) {
File myFile = new File( "C:\\myfile.txt" );
} // end of main
} // end of class definition
If the file does not exist at the path specified and if the file object with the
reference myFile is selected in subsequent code, a FileNotFoundException is
thrown.
Java Programming CoSc3053 35
File Tests and Utilities
 If the file does exist, there are several tests and utilities that are
available as methods of the File class.
 The class that follows illustrates some of these tests and utilities.
import java.io.File;
public class Files {
public static void main( String[ ] args ) {
File myFile = new File( "C:\\myfile.txt" );
System.out.println( myFile.getName( ) );
System.out.println( myFile.getPath( ) );
System.out.println( myFile.exists( ) );
} // end of main
} // end of class definition
Java Programming CoSc3053 36
Reading and Writing with File Stream Classes
 The File streams –
– FileInputStream and FileOutputStream – and
 File readers/writers –
– FileReader and FileWriter
– are used to read from and write to a file.
 A FileReader object can be used to read character streams.
 A BufferedReader object is connected to the FileReader object
used so that its readLine method can be invoked.

Java Programming CoSc3053 37


Reading and Writing with File Stream Classes
 Example:
import java.io.*;
public class FileRead {
public static void main( String[ ] args ) {
BufferedReader br = new BufferedReader (new FileReader(
"c:\\myfile.txt" ) );
String inStr = br.readLine( );
System.out.println( "The contents of the file are: " + inStr );
} // end of main
} // end of class definition
Executing main displays the contents of the existing file named myfile.txt, as
follows:
The contents of the file are: Hello World
Java Programming CoSc3053 38
Reading and Writing with File Stream Classes
 Similarly a FileInputStream object can be used to read a byte stream, as
illustrated by the code below:
import java.io.*;
public class FileRead {
public static void main( String[ ] args ) throws IOException {
FileInputStream fis = new FileInputStream( "c:\\myfile.txt" );
InputStreamReader isr = new InputStreamReader( fis );
BufferedReader br= new BufferedReader( isr );
String s = br.readLine( );
System.out.println( "The contents of the file are: " + s );
} // end of main
} // end of class definition
Executing main displays the contents of the same file named myf ile.txt , as follows:
The contents of the file are: Hello World

Java Programming CoSc3053 39


Data Streams
 Data streams are used to transmit the binary data of primitive data types.
 A DataInputStream object reads primitive data types from an underlying
input stream.
 a DataOutputStream object writes primitive data types to an output
stream.
 An application can use data streams in tandem so that a data output stream
writes data that can be subsequently read back in to the application by a data
input stream.
 The example that follows is a simple illustration of the use of a pair of data
streams. The output data stream writes an int value to a file and the input
data stream reads the value back in and outputs it to the screen.

Java Programming CoSc3053 40


Data Streams…
 Example:
import java.io.*;
public class DataStreams {
public static void main( String[ ] args ) {
// Declare local variables.
DataOutputStream out = null;
DataInputStream in = null;
try {
FileOutputStream fos = new FileOutputStream("C:\\mydatafile.dat");
out = new DataOutputStream( new BufferedOutputStream( fos ) );
// write out an int
out.writeInt( 1234 );
out.close( );
Java Programming CoSc3053 41
Data Streams…
} catch( IOException e ) { }
try {
FileInputStream fis = new FileInputStream( "C:\\mydatafile.dat" );
in = new DataInputStream( new BufferedInputStream( fis ) );
// read in the int that was previously written out
int i = in.readInt( );
in.close( );
System.out.println( "The file contents are: " + i );
}
catch( EOFException e ) { }
catch( FileNotFoundException f ) { }
catch( IOException io ) { }
} // end of main
} // end of class definition
Java Programming CoSc3053 42
Data Streams…
 It should be noted that the writeInt method matches the readInt
method in the class above.
 In general,
– write and read methods used to write and read primitive data
types are matched in this way.
 A further point to note is that the DataInputStream object has a very
convenient way to detect the end of the file that it is reading.
 Its read methods catch an EOFException exception instead of
testing for the return of an invalid value of the primitive being read.

Java Programming CoSc3053 43


End of Chapter 4
Next: Multi-threading concept

Java Programming CoSc3053 49

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy