Java File Handling

Java File Handling tutorial teaches you how to handle files in Java?

Java File Handling

Java File Handling tutorial teaches you how to handle files in Java?

Java File Handling

File Handling in Java

     

File Handling in Java

For file handling in java, the package known as java.io is available. This package contains all the required classes needed to perform input and output (I/O) in Java.

Streams

The sequence of data can be defined as a stream. Java defines two types of streams which are given below :

1. Byte

2. Characters

Byte Stream

For dealing input and output of bytes, byte stream is employed. For reading and writing binary data it is incorporated. Binary Stream uses two abstract classes for input and output. These are InputStream class and OutputStream class respectively. To read data from the source InputStream is used and to write data to a destination OutputStream is used.

The class hierarchy of the Byte Stream is given below :

The byte stream classes are given below :

Byte Stream Classes Detail
InputStream The InputStream is an abstract super class .All the classes representing an input
stream of bytes is the subclass of this super class.
OutputStream The  OutputStream is an abstract super class .All the classes representing an output
 stream of bytes is the subclass of this super class.
FileInputStream In a file system, it gets input bytes from a file.
FileOutputStream Using it you can write data to a File or to a FileDescriptor.
ByteArrayInputStream A ByteArrayInputStream has an internal buffer. This buffer can retain bytes read from the stream
ByteArrayOutputStream Data can be written into a byte array using the output stream of ByteArrayOutputStream.
SequenceInputStream The input streams can be logically concatenated using SequenceInputStream.
StringBufferInputStream  The string's content supplies bytes read to an input stream which is created by an application.
The StringBufferInputStream class allows an application to do this.
FilterInputStream It has some additional input stream used as basic data source, These input streams can provide
transformation of data and extra functionality.
FilterOutputStream All the classes that filter output streams is the subclasses of the FilterOutputStream superclass.
DataInputStream It allows an application to read java's data type using an input stream which is independent of machine.
DataOutputStream It allows an application to write java's data type(primitive) to an output stream.
BufferedInputStream It provides additional functionality to the input stream such as capability to buffer. It also supports reset and mark methods.
BufferedOutputStream The buffered output stream is applied by this class.
PrintStream It provide ability to the other output stream to print several data values' representation.
PipedInputStream The data byte written on piped output stream is provided by PipedInputStream. But before that it must connect to the piped output stream.
PipedOutputStream For creating communication pipe, piped output stream should be connected to piped output stream.
PushbackInputStream To sum up the ability to "push back" or "unread" one byte to other input stream, a PushbackInputStream is used.
RandomAccessFile For accessing a file randomly (for reading or writing) this class is incorporated.

Methods defined by InputStream

After creating InputStream object, you can perform additional operations on the stream using given below methods :

  Methods       Description 
public void close() throws IOException{}  The output stream of a file is closed using this function. Before that it releases any resource. This function throws IOException.
protected void finalize()throws IOException {}  This function clears the connection to the file. It throws an IOException.
public int read(int r)throws IOException{}  This function reads the data from the InputStream and return int which is next byte of data. It also returns
-1 if end of file is reached.
public int read(byte[] r) throws IOException{}  This method reads data equal to length of r from the input stream using array. The total number of bytes read is returned after finishing reading. When end of file reached it returns -1.
public int available() throws IOException{}  This function returns the number of bytes available for reading from file input stream. The return type is int.

Method defined by OutputStream

Once you have OutputStream object in hand then there is a list of helper methods which can be used to write to stream or to do other operations on the stream.

   Methods      Description  
public void close() throws IOException{}  This function closes the output stream of the file and throws IOException.
protected void finalize()throws IOException{} This function closes the connection to the file and throws IOException.
public void write(int w)throws IOException{} Using this function, you can write specified bytes to the output stream.
public void write(byte[] w)  This function is used to write bytes of length equal to w to the output stream from the the mentioned byte array.

Character Stream

For handling the input and output of characters Character Stream is  incorporated, which streamlines internationalization.

The hierarchical distribution of Character stream is different from Byte Stream. The hierarchical tree of Character Stream is topped by the Reader and Writer abstract classes. Reader abstract class is used for input while Writer abstract class is used for output.

The method defined by Reader abstract class is given below :

Function / Method  Description
abstract void close( ) throws IOException The input source is closed using this function.
void mark(int numChars) throws IOException This function set a mark in the input stream at the current point. This Point will remain valid till numChars characters are read.
boolean markSupported( ) If the stream support mark( )/reset( ) , this function returns true.
int read( ) throws IOException The input streams' next available character is return by this function as an integer representation.
int read(char buffer[ ]) throws IOException This function reads the characters from buffer equal to the length of buffer.length and it returns the number of successful characters read.
abstract int read(char buffer[ ],int offset, int numChars) throws IOException This function returns the count of the characters successfully read from buffer starting from buffer[offset] up to numChars.
boolean ready( ) throws IOException If the input is pending, it returns true otherwise false.
void reset( ) throws IOException This function resets the input pointer to the previously set mark.
long skip(long numChars) throws IOException This function skips the number of input characters equal to numChars. It returns the count of actually skipped characters.

The method defined by Writer abstract class is given below :

Function / Method  Description 
Writer append(char ch) throws IOException This function adds ch at the end of the output stream which invoked it. It also returns reference to the stream.
Writer append(CharSequence chars) throws IOException This  function adds the chars to the end of the output stream which invoked it. It also returns a reference to the stream.
Writer append(CharSequence chars, int begin, int end) throws IOException This function adds a sub range of chars to the end of the output stream. It returns a reference to the stream.
abstract void close( ) throws IOException The output stream is closed by this function.
abstract void flush( ) throws IOException This function flushes the buffer of output.
void write(int ch) throws IOException This function writes the character to the output stream. The characters are in the low-order 16 bits of ch .
void write(char buffer[ ]) throws IOException Using this function you can write to the output stream -a complete array of characters .
abstract void write(char buffer[ ],int offset, int numChars) throws IOException This function is used to writes a sub range of numChars characters from the array buffer to the output stream beginning at buffer[offset].
void write(String str) throws IOException Using this function you can writes str to the output stream.
void write(String str, int offset, int numChars) Using this function, from the string str ,you can write a sub range of numChars characters.

The File Class

In spite of classes available to support file I/O, Java has a class named as File, which contains information about a file.  For manipulating a file or the computer's file system, this class is very effective and efficient. This class is used for creation of files and directories, file searching, file deletion etc.

Once you have File object in hand then there is a list of helper methods which can be used manipulate the files, which are given below :

   Methods      Description  
public String getName() This function returns the file or directory's name specified by the pathname.
public String getParent() This function returns the parent directory pathname string. The pathname of the directory is passed to know it's parent pathname string. If the pathname doesn't have parent directory, it returns null.
public File getParent File() This function returns the parent directory abstract pathname and it returns null if it doesn't have parent directory.
public String getPath() To convert the abstract pathname into a pathname string, we use this function.
public boolean isAbsolute() This function return true if this abstract pathname is absolute otherwise returns false.
public String getAbsolutePath()  To find the absolute pathname string of the provided abstract pathname, we incorporate this method.
public boolean canRead()  This function is used to check if the application can read the file provided by this abstract
 pathname. This function returns true if the file name provided by the abstract pathname exists otherwise return false.
public boolean canWrite()  This function is used to check if the application can modify to the file provided through this abstract
 pathname. This function returns true if the file name provided by the abstract pathname exists and allowed to write, otherwise return false.
public boolean exists()  This function returns true if the file name provided by the abstract pathname exists otherwise return false.
public boolean isDirectory()  This function returns true if the file represented by the abstract pathname is a directory otherwise returns false.
public boolean isFile()  This function is used to test whether the file represented by the abstract pathname exist and also checks whether it is a normal file. If it is , it will return true otherwise return false.
public long lastModified()  This function is used to return the last modification time of the file represented by the abstract pathname.
public long length()  This function finds the length of the file of the file represented by the abstract pathname and return it. It returns unspecified if the pathname represented is a directory.
public boolean createNewFile()
 throws IOException
This function is used to create a new file which has the name provided by its abstract pathname. It will return true if the file created successfully otherwise returns false.
public boolean delete()  This function is used to delete the file/directory represented by the  abstract pathname.
public void deleteOnExit()  This function is used to delete the file represented by the  abstract pathname when the virtual machine terminates.
public String[] list()   This function returns an array of strings naming the files and directories in the directory specified by its abstract pathname.  
public String[] list(FilenameFilter filter)  This function returns an array of strings naming the files and directories in the directory specified by its abstract pathname that satisfy the specified filter.
public File[] listFiles()  This functions returns an array of abstract pathnames represented by the files in the directory.
public File[] listFiles(FileFilter filter)  This function returns an array of abstract pathnames represented by the files and directories
 in the directory represented by this abstract pathname that satisfy the
specified filter.
public boolean mkdir()  This function creates the directory named by this abstract pathname. this function returns true if the file created successfully otherwise false.
public boolean mkdirs()  This method creates the directory named by this abstract pathname, including any
necessary but nonexistent parent directories. Returns true if and only ifbr> the directory was created, along with all necessary parent directories;
false otherwise
public boolean renameTo(File dest)  This function renames the file represented by this abstract pathname. 
public boolean setLastModified(long time)  This function is used to set the last modification time of the file/ directory specified by the abstract
pathname.
public boolean setReadOnly()   This function sets the file provided through abstract pathname to read-only mode. If it succeeded, it returns true otherwise returns false.
public String toString()  This function is used to return the pathname string of the abstract pathname provided.

FileReader Class

FileReader class inherits from the InputStreamReader class. For reading streams of characters, this class is used.

Once you have FileReader object in hand then there is a list of helper methods which can be used manipulate the files :

Method / Function Description
public int read() throws IOException This function reads a single character at a time and returns the count of number of character read.
public int read(char [] c, int offset, int len) This function is used to read characters. An array is used to read characters.

FileWriter Class

FileWriter Class inherits from the OutputStreamWriter class. For writing streams of characters, this class is incorporated.

Methods / Function Description
public void write(int c) throws IOException Using this function, you can write a single character.
public void write(char [] c, int offset, int len) Using this function, you can write a part of an array specified by offset(starting) up to the length from offset.
public void write(String s, int offset, int len) Using this function, you can write a part of an String specified by offset(starting) up to the length(specified by len) from offset.