You are on page 1of 35

INPUT-OUTPUT

BASICS
• Not given much importance to console I/O
• Because most real world applications of Java
are not text based console programs
• Graphical oriented interaction
Overview of I/O Streams
• Java programs perform I/O through streams
• To bring in information, a program opens a stream on an
information source (a file, memory, a socket) and reads the
information sequentially, as shown here:

• Similarly, a program can send information to an external


destination by opening a stream to a destination and writing
the information out sequentially, like this:
Reading Writing
1.open a stream 1.open a stream
2.while more information 2.while more information
read information write information
3. close the stream 3.close the stream
• No matter where the data is coming from or going to
and no matter what its type, the algorithms for
sequentially reading and writing data are basically the
same:
• The java.io  package contains a collection of stream
classes that support these algorithms for reading and
writing.
• To use these classes, a program needs to import
the java.io  package.

• import java.io.*;
• Java defines two types of streams: byte and character

• The stream classes are divided into two class


hierarchies, based on the data type (either characters or
bytes) on which they operate.
Byte Stream
• Byte streams are defined by using two class hierarchies.
• At the top are two abstract classes- InputStream  and 
OutputStream
• To read and write 8-bit bytes, programs should use the
byte streams, descendants of InputStream  and 
OutputStream
• InputStream and OutputStream define partial
implementation for several methods that the other stream
classes implement.
• read()- (streams that read 8-bit bytes)
write()- (streams that write 8-bit bytes)
• These streams are typically used to read and write binary
data such as images and sounds.
BYTE STREAM CLASSSES
CLASS HIERARCHY
Character Stream
• Character streams are defined by using two class
hierarchies.
• At the top are two abstract classes- Reader and Writer
• To read and write characters, programs should use the
character streams, descendants of  Reader and Writer
• Reader and Writer  define partial implementation for
several methods that the other stream classes implement.
• read() (streams that read 16-bit characters)
write() (streams that write 16-bit characters)
CHARACTER STREAM CLASSSES
CLASS HIERARCHY
PREDEFINED STREAMS
• The java.lang package defines a class called System
• It contains three predefined stream variables , in,out and err
• These fields are declared as public and static within System
• System.out refers to the standard output stream, i.e console
• System.in refers to the standard input,i.e keyboard
• System.err refers to the standard output stream, i.e console itself

• 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 used to read and
write characters from and to console
READING CONSOLE INPUT
• Use of character oriented stream is preferred
• Console input is accomplished by reading from System.in
• To obtain a character oriented stream that is attached to a console,
wrap System.in in a BufferedReader object
• Commonly used constructor :
BufferedReader(Reader inputReader)
• Reader is an abstract class. One of its concrete subclasses
InputStreamReader converts bytes to characters
• Constructor used :
InputStreamReader(InputStream inputStream)
• System.in is an object of type InputStream
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
READ CHARACTERS FROM CONSOLE
• read() is used which is a member of BufferedReader
int read() throws IOException
• It reads a character from the input stream and returns it as an
integer value.
• It returns -1 when the end of the stream is encountered
READ CHARACTERS FROM CONSOLE
import java.io.*;
class ReadChar
{
public static void main(String args[])
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
char c;
System.out.println("Enter the characters, press q to
exit");
do
{
c=(char)br.read();
System.out.println(c);
}while(c!='q');
}
catch(IOException e)
{
System.out.println("Exception");
}
}
}
OUTPUT
Enter the characters, press q to exit
hello123q
h
e
l
l
o
1
2
3
q
READ STRING FROM CONSOLE
• use readLine() that is a member of BufferedReader class
String readLine() throws IOException
• It returns a String object

import java.io.*;
class ReadString
{
public static void main(String args[])
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter the strings");
System.out.println("Enter stop to quit");
do
{
str=br.readLine();
System.out.println(str);
}while(!str.equals("stop"));
}
catch(IOException e)
{
System.out.println("Exeption "+e);
}
}
}
OUTPUT
E:\MERIN\javaprograms>java ReadString
Enter the strings
Enter stop to quit
good
good
morning
morning
welcome
welcome
stop
stop
READ STRINGS FROM CONSOLE
import java.io.*;
class ReadString1
{
public static void main(String args[])
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String str[]=new String[100];
System.out.println("Enter the strings");
System.out.println("Enter stop to quit");
for(int i=0;i<100;i++)
{
str[i]=br.readLine();
if(str[i].equals("stop"))
break;
}
System.out.println("The entered strings are :");
for(int i=0;i<100;i++)
{
System.out.println(str[i]);
if(str[i].equals("stop"))
break;
}
}
catch(IOException e)
{
System.out.println("Exeption "+e);
}}}
OUTPUT
E:\MERIN\javaprograms>java ReadString1
Enter the strings
Enter stop to quit
hello
good
morning
stop
The entered strings are :
hello
good
morning
stop
Writing Console output
• System.out is used for writing to console
• For real world programs, the recommended method of writing
to the console is through a PrintWriter stream
• Character based stream class
• Constructor used here:
PrintWriter(OutputStream out,boolean flushonNewline)
• out is an object of type OutputStream, flushonNewline controls
whether Java flushes the outputstream everytime a println()
method is called
• If it is true, flushing takes place automatically

• Contains print() and println()


• To write to the console, specify System.out fro the output
stream and flush the stream after each newline
PrintWriter pw=new PrintWriter(System.out,true);
import java.io.*;
class PrintDemo
{
public static void main(String args[])
{
PrintWriter pw=new PrintWriter(System.out,true);
pw.println("Hello World");
int i=-100;
pw.println(i);
double d=4.67768;
pw.println(d);
}
OUTPUT
}
Hello World
-100
4.67768
Reading and Writing Files
• Two of the most often used stream classes are FileInputStream and
FileOutputStream
• To open a file, simple create an object of one of these classes,
specifying the name of the file as the argument to the constructor

FileInputStream(String fileName) throws FileNotFoundException


FileOutputStream(String fileName) throws FileNotFoundException

• Here fileName specifies the name of the file we want to open


• After the operations on the file, we should close it by calling close()
void close() throws IOException
• To read from a file, we can use read() within FileInputStream
int read() throws IOException

• It reads a single byte from the file and returns the byte as an
integer value.
• It returns -1 when end of the file is encountered

• To write to a file, we can use write() within FileOutputStream


void write(int byteval) throws IOException

• It writes the byte specified by byteval to the file


DISPLAY THE CONTENTS OF A TEXT FILE
import java.io.*;
class FileDemo
{
public static void main(String args[])
{
int i;
FileInputStream fin;
try
{
fin=new FileInputStream(args[0]);
}
catch(FileNotFoundException e)
{ System.out.println("File Not Found");
return;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Index");
return;
}
try
{ do
{ i=fin.read();
if(i!=-1) System.out.println((char) i);
}while(i!=-1);
fin.close();
}catch(IOException e){
System.out.println(“IOException”); return;
}
}}
OUTPUT
E:\MERIN\javaprograms>java FileDemo hai.txt
H
e
l
l
o

w
o
r
l
d
COPY ONE FILE TO ANOTHER
import java.io.*;
class CopyFile
{
public static void main(String args[])
{
int i;
FileInputStream fin;
FileOutputStream fout;
try
{
try
{
fin=new FileInputStream(args[0]);
}
catch(FileNotFoundException e)
{ System.out.println("File Not Found");
return;
}
try
{
fout=new FileOutputStream(args[1]);
}
catch(FileNotFoundException e)
{ System.out.println("File Not Found");
return;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Index");
return;
}
try
{ do
{
i=fin.read();
if(i!=-1)
{
System.out.print((char) i);
fout.write(i);
}
}while(i!=-1);
fin.close();
fout.close();
}
catch(IOException e)
{
System.out.println("IOException"); return;
}

}
}
OUTPUT
D:\merin>java CopyFile hai.txt out.txt
Good Morning!!!

You might also like