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

IO Streams and files

The document provides an overview of I/O streams in Java, detailing the types of streams (InputStream and OutputStream) and their subclasses for reading and writing data to files. It covers specific classes such as FileInputStream, FileOutputStream, FileReader, FileWriter, BufferedReader, and RandomAccessFile, including their methods and examples of usage. Additionally, it includes an assignment section with tasks related to file handling and stream classes.

Uploaded by

Chaya Anu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

IO Streams and files

The document provides an overview of I/O streams in Java, detailing the types of streams (InputStream and OutputStream) and their subclasses for reading and writing data to files. It covers specific classes such as FileInputStream, FileOutputStream, FileReader, FileWriter, BufferedReader, and RandomAccessFile, including their methods and examples of usage. Additionally, it includes an assignment section with tasks related to file handling and stream classes.

Uploaded by

Chaya Anu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

I/O Streams

Stream

A stream is a sequence of data. In Java a stream is composed of bytes. A stream is a way of


sequentially accessing a file. It's called a stream because it is like a stream of water that continues to
flow. There are two kinds of Streams:

 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.

 public void close() throws IOException{}


o This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.
 protected void finalize()throws IOException {}
o This method cleans up the connection to the file. Ensures that the close method of
this file output stream is called when there are no more references to this stream.
Throws an IOException.
 public void write(int w)throws IOException{}
o This methods writes the specified byte to the output stream.
 public void write(byte[] w)
o Writes w.length bytes from the mentioned byte array to the OutputStream.

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 −

InputStream f = new FileInputStream("C:/java/hello");

Or

File f = new File("C:/java/hello");


InputStream f = new FileInputStream(f);
Methods
 public void close() throws IOException{}
o This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.
 protected void finalize()throws IOException {}
o This method cleans up the connection to the file. Ensures that the close method of
this file output stream is called when there are no more references to this stream.
Throws an IOException.
 public int read(int r)throws IOException{}
o This method reads the specified byte of data from the InputStream. Returns an int.
Returns the next byte of data and -1 will be returned if it's the end of the file.
 public int read(byte[] r) throws IOException{}
o This method reads r.length bytes from the input stream into an array. Returns the
total number of bytes read. If it is the end of the file, -1 will be returned.
 public int available() throws IOException{}
o Gives the number of bytes that can be read from this file input stream. Returns an
int.
Example:
//FileOutputStream class to store bytes into a file
import java.io.FileOutputStream;
public class fileout{
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("test.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

//FileInputStream class to read from a file to the console


import java.io.*;
public class fileStreamTest {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("test.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

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 FileWriter Class


void write(String text) It is used to write the string into FileWriter.
void write(char c) It is used to write the char into FileWriter.
void write(char[] c) It is used to write char array into FileWriter.
void flush() It is used to flushes the data of FileWriter.
void close() It is used to close the FileWriter.
FileReader Class
The FileReader class of the java.io package can be used to read data (in characters) from files.
It extends the InputSreamReader class.
Create a FileReader
1. Using the name of the file
FileReader input = new FileReader(String name);
2. Using an object of the file
FileReader input = new FileReader(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);
}
}

//Program to add two numbers using BufferedReader class


import java.io.*;
class addtwo{
public static void main(String args[]) throws IOException{
int n1,n2,sum;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a num1");
String str=br.readLine();
n1=Integer.parseInt(str);
System.out.println("Enter a num2");
str=br.readLine();
n2=Integer.parseInt(str);
System.out.println("The Values are "+n1+" "+n2);
sum=n1+n2;
System.out.println("Sum of two numbers "+sum);
}
}

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;

public class randomfile {


static final String FILEPATH ="test.txt";
public static void main(String[] args) {
try {
writeToFile(FILEPATH, "\nI love my country and my people", 31);
System.out.println(new String(readFromFile(FILEPATH, 0, 90)));
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}

//Program to count no. of lines, words and characters in a file


import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader reader = null;
//Initializing charCount, wordCount and lineCount to 0
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
try {
//Creating BufferedReader object
reader = new BufferedReader(new FileReader("test.txt"));
//Reading the first line into currentLine
String currentLine = reader.readLine();
while (currentLine != null) {
//Updating the lineCount
lineCount++;
//Getting number of words in currentLine
String[] words = currentLine.split(" ");
//Updating the wordCount
wordCount = wordCount + words.length;
//Iterating each word
for (String word : words) {
//Updating the charCount
charCount = charCount + word.length();
}
//Reading next line into currentLine
currentLine = reader.readLine();
}
//Printing charCount, wordCount and lineCount
System.out.println("Number Of Chars In A File : "+charCount);
System.out.println("Number Of Words In A File : "+wordCount);
System.out.println("Number Of Lines In A File : "+lineCount);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
reader.close(); //Closing the reader
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}

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.

You might also like