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

Unit6 - File IO

The document discusses Java file input/output streams. It describes stream classes like InputStream and OutputStream and byte streams vs character streams. It provides details on FileInputStream, FileOutputStream, FileReader including their constructors and methods. It also includes an example to copy contents from one file to another using byte streams.

Uploaded by

shree500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit6 - File IO

The document discusses Java file input/output streams. It describes stream classes like InputStream and OutputStream and byte streams vs character streams. It provides details on FileInputStream, FileOutputStream, FileReader including their constructors and methods. It also includes an example to copy contents from one file to another using byte streams.

Uploaded by

shree500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Java Programming(22412)

Chapter 6
Marks 12
File I/O

6.1 Stream classes:


 Java performs I/O through Streams.
 A stream can be defined as a sequence of data.
 A stream can represent many different kinds of sources and destinations, including disk files, devices,
other programs, and memory arrays.
 InputStream and OutputStream are the basic stream classes in Java. The InputStream is used to read data
from a source and the OutputStream is used for writing data to a destination.
 The java. IO package contain a large number of stream classes that provide capabilities for processing
all types of data. These classes may be categorized into two groups based on the data type on which they
operate.
 Java defines two types of streams. They are,
1. Byte Stream
2. Character Stream.

 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

6.2 Byte stream


 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.
 Byte streams are used to read or write binary data. Byte streams can read or write the files containing
ASCII characters that range from 0 to 255. Byte streams can copy the files containing English letters
only.
 There are two types of Character stream classes 1) InputStream 2) OutputStream
 There are many classes related to byte stream.

1
Java Programming(22412)

 Following are the byte oriented input stream classes.


1) ByteArrayInputStream 4) FileInputStream
2) PipedInputStream 5) DataInputStream
3) BufferedInputStream 6) ObjectInputStream
 Following are the byte oriented input stream classes
1) ByteArrayOutputStream 4) FileOutputStream
2) PipedOutputStream 5) DataOutputStream
3) BufferedOutputStream 6) ObjectOutputStream

 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);

Creates a file output stream to write to the file represented by the


specified File object. If exist and append value is true then
FileOutputStream(File file, boolean appends the data at the end of file.
append) For example:
File f=new File (“Text1.txt”);
FileOutputStream fos=new FileOutputStream (f,true);

Creates a file output stream to write to the file represented by the


specified File object. If exist and append value is true then
FileOutputStream(String filename,
appends the data at the end of file.
boolean append)
For example:
FileOutputStream fos=new FileOutputStream (“Text1.txt”,true);

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

FileOutputStream fos=new FileOutputStream("file1.txt");

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);
}
}
}

6.3 Character stream


 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. Character streams can read, write and copy
the files containing other than English characters. Characters streams can do with English characters
also as ASCII code is a subset of Unicode.
 There are two types of Character stream classes 1) Reader 2) Writer
 There are many classes related to Character stream.
 Following are the character oriented reader classes .
1) CharArrayReader 2) FileReader 3) PipedReader
4) StringReader 5) BufferedReader
 Following are the byte oriented writer classes
1) CharArrayWriter 2) FileWriter 3) PipedWriter
4) StringWriter 5) BufferedWriter

 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)

FileWriter fw=new FileWriter("file2.txt");


Output:
int ch=0;
while(ch!=-1) File copied Successfully
{
ch=fr.read();
fw.write((char)ch);
}
System.out.println("File copied Successfully");
fr.close();
fw.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}

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.

 Serializing an Object: (Writing an object to a file)


 The ObjectOutputStream class is used to serialize an object.
 Its constructor is:
ObjectOutputStream (FileOutputStream fos)

 It contains the following method for serializing an object:

public final void writeObject(Object x) throws IOException

 Deserializing an Object: (Reading an object from a file)


 The ObjectInputStream class is used to deserialize an object.
 Its constructor is:
ObjectInputStream (FileInputStream fis)
6
Java Programming(22412)

 It contains the following method for deserializing an object:

public final Object readObject() throws IOException, ClassNotFoundException


 This method retrieves the next Object out of the stream and deserializes it. The return value is
Object, so we will need to cast it to its appropriate data type.

WAP to demonstrate Serializing and Deserializing an object


import java.io.*;
class Employee implements Serializable
{ Output:
int emp_id; Serialized data is saved in employee.txt
String emp_name;
float salary; Deserialized data from employee.txt
Emp_id=101
Employee(int id,String n,float s) Emp_name=Sachin
{ Emp salary=20000.0
emp_id=id;
emp_name=n;
salary=s;
}
void show()
{
System.out.println("Emp_id="+emp_id);
System.out.println("Emp_name="+emp_name);
System.out.println("Emp salary="+salary);

}
}
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)

WAP to demonstrate File class


import java.io.File;
class FileDemo
{
public static void main(String args[])
{ File f1 = new File("/FileDemo.java");

System.out.println ("File Name: " + f1.getName ()); Output:


System.out.println ("Path: " + f1.getPath ()); File Name: FileDemo.java
System.out.println ("Parent: " + f1.getParent ()); Path: \FileDemo.java
System.out.println ("Abs Path: " + f1.getAbsolutePath ()); Parent: \
System.out.println ("is Exists:"+f1.exists ()); Abs Path: F:\FileDemo.java
System.out.println ("is Directory:" + f1.isDirectory()); is Exists: true
System.out.println ("is File:"+f1.isFile()); is Directory: false
System.out.println ("File size: " + f1.length() + " Bytes"); is File:true
} File size: 568 Bytes
}

Handling Primitive Types


 There are two classes provided by Java to support data streams to handle primitive data types such as
byte, short, int long, double, etc.
1) DataInputStream
2) DataOutputStream
 DataInputStream class is used to read primitive Java data types from an input stream in a machine-
independent way.
 While the DataOutputStream class is used to write primitive Java data types to an output stream in a
portable way.

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(" ");

System.out.println("Number of words in the given file are " +data.length);


System.out.println("Number of chars in the given file are " +array. length);
}
}

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)

5. Write a program that will count no. of characters in a file.


6. Write a program to count number of words from a text file using stream classes.
7. Write a program to copy contents of one file to another file using character stream class.
8. Write a program to copy contents of one file to another file using byte stream class.

11

You might also like