0% found this document useful (0 votes)
4 views

JavaIOStream

Uploaded by

Nikunj Shah3540
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JavaIOStream

Uploaded by

Nikunj Shah3540
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Java I/O

Streams
Streams
• Java programs perform I/O through streams.
• A stream is an abstraction that either produces or consumes information. A stream
is linked to a physical device by the Java I/O system. All streams behave in the same
manner, even if the actual physical devices to which they are linked differ. Thus, the
same I/O classes and methods can be applied to different types of devices.
• This means that an input stream can abstract many different kinds of input: from a
disk file, a keyboard, or a network socket.
• Likewise, an output stream may refer to the console, a disk file, or a network
connection. Streams are a clean way to deal with input/output without having
every part of your code understand the difference between a keyboard and a
network, for example. Java implements streams within class hierarchies defined in
the java.io package.
Stream
• Byte Streams and Character Streams:
• Java defines two types of streams: byte and character. Byte streams
provide a convenient means for handling input and output of bytes.
Byte streams are used, for example, when reading or writing binary
data.
• Character streams provide a convenient means for handling input and
output of characters. They use Unicode and, therefore, can be
internationalized. Also, in some cases, character streams are more
efficient than byte streams.
Streams
• The Byte Stream Classes:
• Byte streams are defined by using two class hierarchies. At the top are
two abstract classes: InputStream and OutputStream. Each of these
abstract classes has several concrete subclasses that handle the
differences among various devices, such as disk files, network
connections, and even memory buffers.
• To use the stream classes, you must import java.io.
Streams
• The abstract classes InputStream and OutputStream define several
key methods that the other stream classes implement. Two of the
most important are read( ) and write( ), which, respectively, read and
write bytes of data. Each has a form that is abstract and must be
overridden by derived stream classes.
• The Character Stream Classes:
• Character streams are defined by using two class hierarchies. At the
top are two abstract classes: Reader and Writer. These abstract
classes handle Unicode character streams. Java has several concrete
subclasses of each of these.
Streams
• The abstract classes Reader and Writer define several key methods
that the other stream classes implement. Two of the most important
methods are read( ) and write( ), which read and write characters of
data, respectively. Each has a form that is abstract and must be
overridden by derived stream classes.
System
• All Java programs automatically import the java.lang package.
• This package defines a class called System, which encapsulates several
aspects of the run-time environment. For example, using some of its
methods, you can obtain the current time and the settings of various
properties associated with the system. System also contains three
predefined stream variables: in, out, and err. These fields are declared
as public, static, and final within System. This means that they can be
used by any other part of your program and without reference to a
specific System object.
System
• System.out refers to the standard output stream. By default, this is the
console.
• System.in refers to standard input, which is the keyboard by default.
• System.err refers to the standard error stream, which also is the console
by default.
• However, these streams may be redirected to any compatible I/O device.
• System.in is an object of type InputStream;
• System.out and System.err are objects of type PrintStream. These are
byte streams, even though they are typically used to read and write
characters from and to the console.
Stream
• In Java, console input is accomplished by reading from System.in. To
obtain a character-based stream that is attached to the console, wrap
System.in in a BufferedReader object. BufferedReader supports a
buffered input stream.
• BufferedReader(Reader inputReader)
• Here, inputReader is the stream that is linked to the instance of
BufferedReader that is being created. Reader is an abstract class. One of
its concrete subclasses is InputStreamReader, which converts bytes to
characters. To obtain an InputStreamReader object that is linked to
System.in, use the following constructor:
• InputStreamReader(InputStream inputStream)
Stream
• Because System.in refers to an object of type InputStream, it can be
used for inputStream. Putting it all together, the following line of code
creates a BufferedReader that is connected to the keyboard:
• BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
• After this statement executes, br is a character-based stream that is
linked to the console through System.in.
Stream
• Reading Characters:
• To read a character from a BufferedReader, use read( ). The version of
read( ) that we will be using is :
• int read( ) throws IOException
• Each time that read( ) is called, it reads a character from the input
stream and returns it as an integer value. It returns –1 when an
attempt is made to read at the end of the stream. As you can see, it
can throw an IOException.
• The following program demonstrates read( ) by reading characters
from the console until the user types a "q."
Stream
• // Use a BufferedReader to read characters from the console.
• import java.io.*;

• class BRRead {
• public static void main(String args[]) throws IOException
• {
• char c;
• BufferedReader br = new
• BufferedReader(new InputStreamReader(System.in));
Stream
• System.out.println("Enter characters, 'q' to quit.");
• // read characters
• do {
• c = (char) br.read();
• System.out.println(c);
• } while(c != 'q');
• }
•}
Stream
• Enter characters, 'q' to quit.
• 123abcq
• 123abcq
• This output may look a little different from what you expected
because System.in is line buffered, by default. This means that no
input is actually passed to the program until you press enter. As you
can guess, this does not make read( ) particularly valuable for
interactive console input.
Reading Strings
• Reading Strings:
• To read a string from the keyboard, use the version of readLine( ) that
is a member of the BufferedReader class. Its general form is:
• String readLine( ) throws IOException
• do {
• str = br.readLine();
• System.out.println(str);
• } while(!str.equals("quit"));
Reading String Array
• Create an array of String objects and then reads in lines of text,
storing each line in the array. It will read up to 100 lines or until you
enter "stop." Use BufferedReader to read from the console.
• for(int i=0; i<100; i++) {
• str[i] = br.readLine();
• if(str[i].equals("stop")) break;
• }
Console Output
• Console output is most easily accomplished with print( ) and println( ).
• These methods are defined by the class PrintStream (which is the type
of object referenced by System.out).
• Even though System.out is a byte stream, using it for simple program
output is still acceptable.
• However, a character-based alternative is there.
• Because PrintStream is an output stream derived from OutputStream,
it also implements the low-level method write( ). Thus, write( ) can be
used to write to the console. The simplest form of write( ) defined by
PrintStream is:
Console Output
• class WriteDemo {
• public static void main(String args[]) {
• int b;

• b = 'A';
• System.out.write(b);
• System.out.write('\n');
• }
•}
PrintWriter
• PrintWriter is one of the character-based classes. Using a character-
based class for console output makes internationalizing your program
easier.
• PrintWriter defines several constructors. The one we will use is:
• PrintWriter(OutputStream outputStream, boolean flushingOn)
• Here, outputStream is an object of type OutputStream, and
flushingOn controls whether Java flushes the output stream every
time a println( ) method (among others) is called. If flushingOn is true,
flushing automatically takes place. If false, flushing is not automatic.
PrintWriter
• PrintWriter supports the print( ) and println( ) methods.
• Thus, we can use these methods in the same way as we used them
with System.out.
• If an argument is not a simple type, the PrintWriter methods call the
object’s toString( ) method and then display the result.
• To write to the console by using a PrintWriter, specify System.out for
then output stream and automatic flushing.This line of code creates a
• PrintWriter that is connected to console output:
• PrintWriter pw = new PrintWriter(System.out, true);
PrintWriter
• PrintWriter pw = new PrintWriter(System.out, true);

• pw.println("This is a string");
• int i = -7;
• pw.println(i);
• double d = 4.5e-7;
• pw.println(d);
FileInputStream
• Two of the most often-used stream classes are FileInputStream and
FileOutputStream, which create byte streams linked to files. To open a
file, you simply create an object of one of these classes, specifying the
name of the file as an argument to the constructor. Although both
classes support additional constructors, the following are the forms
that we will be using:
• FileInputStream(String fileName) throws FileNotFoundException
• FileOutputStream(String fileName) throws FileNotFoundException
FileOutputStream
• Here, fileName specifies the name of the file that you want to open.
When you create an input stream, if the file does not exist, then
FileNotFoundException is thrown.
• For output streams, if the file cannot be opened or created, then
FileNotFoundException is thrown.
• FileNotFoundException is a subclass of IOException.
• When an output file is opened, any preexisting file by the same name
is destroyed.
FileOutputStream
• When you are done with a file, you must close it. This is done by
calling the close( ) method, which is implemented by both
FileInputStream and FileOutputStream. It is shown here:
• void close( ) throws IOException
• Closing a file releases the system resources allocated to the file,
allowing them to be used by another file. Failure to close a file can
result in “memory leaks” because of unused resources remaining
allocated.
FileInputStream
• FileInputStream fin;
• fin = new FileInputStream(args[0]);
• do {
• i = fin.read();
• if(i != -1) System.out.print((char) i);
• } while(i != -1);
• fin.close();

You might also like