Unit6 - File IO
Unit6 - File IO
Chapter 6
Marks 12
File I/O
Java byte streams are used to perform input and output of 8-bit bytes. Byte streams provide a convenient
means for handling input and output of bytes.
Java Character streams are used to perform input and output for 16-bit Unicode. Character streams
provide a convenient means for handling input and output of characters. They use Unicode and,
therefore, can be internationalized
1
Java Programming(22412)
FileInputStream
A FileInputStream is an InputStream to obtain bytes from a file.
It can read byte oriented data.
Constructor
Constructor Description
Creates a file input stream to read from the file represented by
the File object.
FileInputStream(File file) For example:
File f=new File (“Text1.txt”);
FileInputStream fis=new FileInputStream (f);
Creates an input stream to read from the file.
FileInputStream(String filename) For example:
FileInputStream fis=new FileInputStream (“Text1.txt”);
Methods of FileInputStream:
Method Description
public int read ( ) throws IOException This method reads a byte from the InputStream. Returns the
next byte of data and -1 will be returned if it's end of file.
public int read (byte b[ ]) throws IOException This method reads array of bytes into b. -1 will be returned if
it's end of file.
public int read (byte b[ ], int n, int m) This method reads m bytes into b starting from nth byte. -1
throws IOException will be returned if it's end of file.
public int available( ) throws IOException Returns the number of bytes that can be read from this file
input stream.
public void close ( ) throws IOException This method closes the input stream.
public void skip(int n) throws IOException This method skips n bytes from the InputStream.
public void reset( ) throws IOException Goes back to the beginning of the stream.
2
Java Programming(22412)
FileOutputStream
A FileOutputStream is an OutputStream to write bytes to a file.
It can write byte oriented data.
Constructor
Constructor Description
Creates an output stream to write to the file.
FileOutputStream (String filename) For example:
FileOutputStream fos=new FileOutputStream(“Text1.txt”);
Creates a file output stream to write to the file represented by
the File object.
FileOutputStream(File file) For example: File f=new File (“Text1.txt”);
FileOutputStream fos=new FileOutputStream (f);
Methods of FileOutputStream:
Method Description
void write(byte b) throws IOException This method writes a byte to the output stream.
void write(byte[ ] b) throws IOException This method writes all bytes from the array to the output
stream.
void write(byte[] b, int n, int m) throws This method writes m bytes from byte array starting from
IOException nth to the output stream.
void flush( ) throws IOException This method flushes the output stream.
public void close () throws IOException This method closes the output stream.
Write a program to copy contents of one file in another file using byte stream classes.
import java.io.*;
class CopyByte
{
public static void main(String args[])
{
try
{ FileInputStream fis=new FileInputStream("myfile.txt");
3
Java Programming(22412)
int b=0;
Output:
while(b!=-1)
{ File copied Successfully
b=fis.read();
fos.write(b);
}
System.out.println("File copied Successfully");
fis.close();
fos.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
FileReader
FileReader is used for reading streams of characters.
Constructor
Constructor Description
Creates a file reader stream to read from the file represented by
the File object.
FileReader(File file)
For example:File f=new File (“Text1.txt”);
FileReader fr=new FileReader (f);
Creates reader stream to read from the file.
FileReader(String filenamee) For example:FileReader fr=new FileReader(“Text1.txt”);
4
Java Programming(22412)
Methods of FileReader:
Method Description
public int read ( ) throws IOException This method reads a character. -1 will be returned if it's end
of file.
public int read (char c[ ]) throws IOException Reads characters into an array. -1 will be returned if it's end
of file.
public int read (char c[ ], int n, int m) throws This method reads m characters into c starting from nth
IOException character. -1 will be returned if it's end of file.
public void close ( ) throws IOException This method closes the reader stream.
public void skip(int n) throws IOException This method skips n characters from the reader Stream.
public void reset( ) throws IOException Goes back to the beginning of the stream.
FileWriter
FileWriter is used for reading streams of characters.
Constructor
Constructor Description
Creates a file writer stream to write to the file represented by
the File object.
FileWriter(File file)
For example: File f=new File (“Text1.txt”);
FileWriter fw=new FileWriter (f);
Creates writerr stream to write to the file.
FileWriter(String filename) For example: FileWriter fw=new FileWriter(“Text1.txt”);
Methods of FileWriter
Method Description
void write(char c) throws IOException This method writes a character to the output stream.
void write(char[ ] c) throws IOException This method writes all characters from the array to the
output stream.
void write(char[] c, int n, int m) throws This method writes m characers from character array
IOException starting from nth to the output stream.
void flush( ) throws IOException This method flushes the output stream.
public void close () throws IOException This method closes the output stream.
Write a program to copy contents of one file in another file using character stream
classes.
class CopyChar
{
public static void main(String args[])
{
try
{
FileReader fr=new FileReader("myfile.txt");
5
Java Programming(22412)
Serialization:
Serialization is a process in which current state of Object will be saved in stream of bytes.
In serialization, Object can be represented as a sequence of bytes that includes the object's data as well
as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and desterilized.
Serialization will translate the Object state to Byte Streams. This Byte stream can be used for different
purpose.
1) Write to Disk
2) Store in Memory
3) Sent byte stream to other platform over network
4) Save byte stream in Database
To serialize an object, we need to implement java.io.Serializable interface.
}
}
class SerializeDeserialize
{
public static void main(String [] args)
{
Employee emp = new Employee(101,"Sachin",20000f);
try
{
//Serialization Process
FileOutputStream fos=new FileOutputStream("employee.txt");
ObjectOutputStream out= new ObjectOutputStream(fos);
out.writeObject(emp);
System.out.println("Serialized data is saved in employee.txt");
out.close();
fos.close();
7
Java Programming(22412)
//Deserialization Process
FileInputStream fis=new FileInputStream("employee.txt");
ObjectInputStream in= new ObjectInputStream(fis);
Employee e1=(Employee)in.readObject();
System.out.println ("\nDeserialized data from employee.txt");
e1.show();
in.close();
fis.close();
}
catch (Exception e)
{
System.out.println (e);
}
}
}
6.4 File classes:
The primary class used to handle files is called File. The File class is part of the java.io package.
It deals directly with files and the file system. That is, the File class does not specify how information is retrieved
from or stored in files; it describes the properties of a file itself.
A File object is used to obtain or manipulate the information associated with a disk file, such as the permissions,
time, date, and directory path, and to navigate subdirectory hierarchies.
Constructor:
File (String pathname)
Creates a new File instance by converting the given pathname string into an abstract pathname
Methods:
Method Description
public String getName() Returns the name of the file or directory.
public String getParent() Returns the name of a parent directory.
public String getPath() Returns the file pathname.
public boolean isAbsolute() Returns true if this abstract pathname is absolute, false
otherwise
public boolean exists() Returns true if and only if the file or directory denoted by this
abstract pathname exists; false otherwise
public boolean isDirectory() Returns true if and only if the file denoted by this abstract
pathname exists and is a directory; false otherwise.
public boolean isFile() Returns true if and only if the file denoted by this abstract
pathname exists and is a normal file; false otherwise.
public long length() Returns the length of the file.
public String[] list() Returns an array of strings naming the files and directories in
the directory denoted by this abstract pathname.
8
Java Programming(22412)
1) DataOutputStream:
Constructor
DataOutputStream(OutputStream out): Creates a new data output stream to write data to the
specified underlying output stream
Methods:
Method Description
public final void write(byte[] w, Writes m bytes from the specified byte array b starting at
int n, int m)throws IOException nth byte, to the stream
Public final int write(byte [] b) Writes the bytes from byte array to data output stream.
throws IOException Returns the total number of bytes written into the buffer.
public final void writeBooolean() Writes the boolean data into the output stream as bytes.
throws IOException
public final void writeByte() Writes the byte data into the output stream as bytes.
throws IOException
9
Java Programming(22412)
public final void writeShort() Writes the short data into the output stream as bytes.
throws IOException
public final void writeInt() throws Writes the int data into the output stream as bytes.
IOException
Public void flush() throws Flushes the data output stream.
IOException
public final void Writes out the string to the output stream as a sequence of
writeBytes(String s) throws bytes
IOException
public final void writeChar(int v) Writes a char to the underlying output stream as a 2-byte
throws IOException value
public final void Writes out the string to the output stream as a sequence of
writeChars(String s) throws characters
IOException
Write a program that will count no. of characters & words in a file.
import java.io.*;
public class Count
{
public static void main(String args[]) throws Exception
{
File file = new File("data.txt");
FileReader fr=new FileReader(file);
char[] array=new char[(int)file.length()];
fr.read(array);
String s=new String(array);
String [] data = s.split(" ");
Questions on Chapter 6
1. What are stream classes? List any two input stream classes from character stream.
2. Write any two methods of File and FileInputStream class each.
3. Write any four methods of file class with their use.
4. What are streams? Write any two methods of character stream classes.
10
Java Programming(22412)
11