B.Sc. CSIT 7th Semester Advanced Java Programming

File Handling in JAVA

Introduction

File is a location that is used to store the information. File handling in java is defined as reading and writing data in the file. Java I/O is used to  process the input and produce the output based on the output. Java uses the java.io packages which contains all the input  and output operation.Java uses the stream to make the input and output operation.

Stream is a sequence of data. They are composed of byte. There are two stream which are automatically created and attached with  console. They are:

  • System.in:Input stream
  • System.out:output stream
file handling in java
concept of stream

 Java uses the input stream to read the data from the source,files,devices etc  and the output stream to write the data in the destination.The package java.io provides two set of class hierarchies  i.e one for handling reading and writing of bytes and another for handling reading and writing characters.

Byte Stream Classes

Java byte streams are used to perform input and output of 8-bit bytes.Inputstream  and Outputstream are the root of hierarchies handling reading and writing of bytes respectively. FileInputStream and FileOutputStream are mainly used classes in Byte Stream.

InputStream is an abstract class that defines Java’s model of streaming byte input. Inputstream class has few  methods for reading bytes. All of the methods in this class will throw an IOException on error conditions.

The following table shows methods of inputstream class for reading bytes:

MethodsDescription
Int read()Reads the next bytes of data from this input stream.Returns an integer representation of the next available byte of input. –1 is returned when the end of the file is encountered. 
Int read(byte b[])Reads upto to b.length bytes of data from the inputstream into an array of bytes and  returns the actual number of bytes that were successfully read. –1 is returned when the end of the file is encountered. 
int read(byte buffer[ ], int offset,int numBytes) Reads up to len bytes of data from this input stream into an array of bytes,but starts at offset bytes into the array.
void close( ) Closes the input source. Further read attempts will generate an IOException. 
void mark(int numBytes) Places a mark at the current point in the input stream that will remain valid until numBytes bytes are read. 
void reset( ) Resets the input pointer to the previously set mark. 

OutputStream is an abstract class that defines streaming byte output.  All of the methods in this class return a void value and throw an IOException in the case of errors.The following table shows methods of outputstream class for writing bytes:

MethodsDescription
Void write(int b)Writes the specified byte to this output stream.Note that the parameter is an int, which allows you to call write( ) with expressions without having to cast them back to byte. 
void write(byte buffer[ ]) Writes b.length bytes from the specified byte array to this output stream.
void write(byte buffer[ ], int offset,numBytes)Writes len bytes form the specified byte array starting at offset off to this output stream
void close( ) Closes the output stream. Further write attempts will generate an IOException. 
void flush( )Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers.

Example:

file handling in java

Input.txt

file handling in java

Output.txt

file handling in java

Character stream classes

Character streams are used to perform input and output for 16 bit unicode.At the top of the character stream hierarchies are the Reader and Writer abstract classes.  Reader is an abstract class that defines Java’s model of streaming character input. Writer is an abstract class that defines streaming character output.  All of the methods in this class will throw an IOException on error condition.Character stream classes uses FileWriter and FileReader  classes to read and write data from text files.

FileReader

The FileReader class creates a Reader that can be used to read the contents of a file. Its two most commonly used constructors of filereader are:

  •  FileReader(String filePath)  
  •   FileReader(File fileObj) 

 Here, filePath is the full path name of a file, and fileObj is a File object that describes the file. 

FileWriter

FileWriter creates a Writer that you can use to write to a file.  Its most commonly used constructors of FileReader  are :

  • FileWriter(String filePath) 
  • FileWriter(String filePath, boolean append)
  •  FileWriter(File fileObj) 
  • FileWriter(File fileObj, boolean append) 

Example:

file handling in java

Input.txt file:

file handling in java

Ouput1.txt file

file handling in java

Random Access File

Random Access file  class in java.IO API allows us to move back and forth in the file and we can read and write the content in any required place of file.we use Random Access file to find or write data anywhere in a file..A random access file behaves like a large array of bytes.Before using Random AccessFile class,it must be instantiated it as below:

RandomAccessFile file=new RandomAccessFile(file-name,mode)

 Class Constructor

  • RandomAccessFile(File file, String mode):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):Creates a random access file stream to read from, and optionally to write to, a file with the specified name.

Class Method

MethodDescription
Void close()This method closes this random access file stream and releases any system resources associated with the stream.
FileChannel getChannel()This method  returns the unique FileChannel object associated with this file.
Int readInt()This method reads a signed 32-bit integer from this file.
String readUTF()This method reads in a string from this file.
Void write(int b)This method writes the specified byte to this file.
Int read()This method reads a byte of data from this file.
long length()This method return the length of this file

Example:

import java.io.IOException;  

import java.io.RandomAccessFile; 

public class randomaccess{

 static final String FILEPATH =”file.TXT”; 

    public static void main(String args[]){

       try {  

            System.out.println(new String(readFromFile(FILEPATH, 0, 18)));  

            writeToFile(FILEPATH, “I have my computer”, 18); 

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

    }  

}  

Also Read: Fudamental Programming Structure in Java

About Author

Sarina Sindurakar