IO Streams and files
IO Streams and files
Stream
OutputStream Java application uses an output stream to write data to a destination, it may
be a file, an array, peripheral device or socket.
InputStream Java application uses an input stream to read data from a source, it may be a
file, an array, peripheral device or socket.
The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream in
the java.io package supports many data such as primitives, object, localized characters, etc.
Stream Hierarchy
Byte Streams
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are
descended from InputStream and OutputStream.
There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file
I/O byte streams, FileInputStream and FileOutputStream.
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if it
doesn't already exist, before opening it for output.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the keyword new
and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file −
Or
FileWriter Class
The FileWriter class of the java.io package can be used to write data (in characters) to files.
It extends the OutputStreamWriter class.
Create a FileWriter
1. Using the name of the file
FileWriter output = new FileWriter(String name);
2. Using an object of the file
FileWriter input = new FileWriter(File fileObj);
Methods of FileReader
int read() It is used to return a character in ASCII form. It returns -1 at the end of file.
void close() It is used to close the FileReader class.
Example
//FileWriter to write characters into a file
import java.io.FileWriter;
public class Filewrite{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("FR.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
//FileReader to read characters from a file
import java.io.FileReader;
public class Fileread {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("FR.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
BufferedReader Class
The BufferedReader class of the java.io package can be used with other readers to read data (in
characters) more efficiently.
It can be used to read data line by line by readLine() method. It makes the performance fast.It
extends the abstract class Reader.
Constructors
BufferedReader(Reader rd) It is used to create a buffered character input stream that
uses the default size for an input buffer.
BufferedReader(Reader rd, int size) It is used to create a buffered character input
stream that uses the specified size for an input buffer.
Methods
int read() It is used for reading a single character.
String readLine() It is used for reading a line of text.
boolean ready() It is used to test whether the input stream is ready to be read.
It closes the input stream and releases any of the system
void close()
resources associated with the stream.
Example
//Program to input values from the user using BufferedReader
import java.io.*;
class bufferinput{
public static void main(String args[]) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a String");
String str=br.readLine();
System.out.println("The input is "+str);
}
}
RandomFile Access
The Java RandomAccessFile class in the Java IO API allows you to move navigate a file and read from
it or write to it as you please. You can replace existing parts of a file too.
Constructor
RandomAccessFile(File file, String mode)
o Creates a random access file stream to read from, and optionally to write to, the file
specified by the File argument.
RandomAccessFile(String name, String mode)
o Creates a random access file stream to read from, and optionally to write to, a file
with the specified name.
Method
void close() It closes this random access file stream and releases any
system resources associated with the stream.
FileChannel getChannel() It returns the unique FileChannel object associated with this
file.
int readInt() It reads a signed 32-bit integer from this file.
String readUTF() It reads in a string from this file.
void seek(long It sets the file-pointer offset, measured from the beginning
pos) of this file, at which the next read or write occurs.
void writeDouble( It converts the double argument to a long using the
double v) doubleToLongBits method in class Double, and then writes
that long value to the file as an eight-byte quantity, high
byte first.
void writeFloat(flo It converts the float argument to an int using the
at v) floatToIntBits method in class Float, and then writes that int
value to the file as a four-byte quantity, high byte first.
void write(int b) It writes the specified byte to this file.
int read() It reads a byte of data from this file.
long length() It returns the length of this file.
void seek(long It sets the file-pointer offset, measured from the beginning
pos) of this file, at which the next read or write occurs.
Example
import java.io.IOException;
import java.io.RandomAccessFile;
Assignment
1. Write a java program to count the number of vowels in a file.
2. Explain the difference between File input output stream classes to File reader writer classes
with an example.
3. Explain the benefits of using RandomAccessFile class.
4. How BufferedReader class is advantageous than Scanner class to accept inputs from user?
Explain.
5. Write short notes on IO Stream classes.