Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 50

1. What is Java I/O?

The Java I/O means Java Input/Output. It is provided by the java.io package. This
package has an InputStream and OutputStream. Java InputStream is defined for reading
the stream, byte stream and array of byte stream.
2. Classes and Interfaces of the I/O Streams
The following listing of classes provided by the java.io package shown in the given table.

   
3. Reading Text from the Standard Input 
Java provides the standard I/O facilities for reading text through either from the file or
from the keyboard on command line. This program illustrates how to use standard input
to read the user input.
4. Working With the Files
The File class deals with the machine dependent files in a machine-independent manner
i.e. it is easier to write platform-independent code that examines and manipulates files
using the File class. This class is available in the java.lang package.

o Create a File 
o Constructing a File Name path
o Read the File
o Write to a File
o Appending to a File
o Getting the Size of a File
o Count lines of a particular file
o Renaming a File or Directory
o Copying a File to Another File
o Copying Multiple Files 
o Moving a File or Directory to Another Directory
o Deleting a File or Directory
o Change a File timestamp
o Create a Temp File
o Delete a Temp File   
o Getting an absolute path and Parents of a Filename

5. Working with a Directory


In the section, you will learn how a directory is created. Apart from this, you will also be
aware from some manipulations that are performed 
on a directory.

o Creating a Directory
o Copying a Directory or file
o Traversing files and directories
o Getting the Current Working Directory
o Getting the Modification Time of a File or Directory
o Listing Files or Subdirectories 
o Deleting a File
6. Filter I/O Streams
Like I/O streams, Filter streams are also used to manipulate the data reading from an
underlying stream.. Apart from this, it allows the user to make a chain using multiple
input stream so that, the operations that are to be applied on this chain, may create a
combine effects on several filters. 
o Introduction 
o Write to a file
o Read the file
o Another Streams

7. Overview of I/O Data Streams


Data streams are filtered streams that perform binary I/O operation on primitive data type
values ( boolean, char, byte, short, int, long, etc.) as well as on String values. If you need
to work with data that is not represented as bytes or characters then you can use Data
Streams.

o Working with PrintStream

8. Using a Random Access File


n this section, you will learn about the Random Access File class provided by java. io
package. This is a class that allows you to read and write arbitrary bytes, text, and
primitive Java data types from or to any specified location in a file. 
   
9. Converting a Filename Path to a URL
In this section, you will learn, how a Filename path is converted to a URL and vice
versa . URL stands for Uniform Resource Locator.
                    
10. Making Tokens of a Java Source Code
In Java, The StreamTokenizer class is used for simple parsing of a Java source file into
tokens. This class takes an input stream, breaks up the ASCII text in a file and parses it
into "tokens". It allows the tokens to be read one at a time.
    
11. Introduction to Encoding
Java programs use Unicode text internally. It supports standard UTF-8 when reading and
writing strings through the InputStreamReader and the OutputStreamWriter. 
o Reading UTF-8 Encoded Data
o Writing UTF-8 Encoded Data
o Reading ISO Latin-1 Encoded Data
o Writing ISO Latin-1 Encoded Data
  
12. Serializing an Object
Serialization is the process of saving an object in a storage medium (such as a file, or a
memory buffer) or to transmit it over a network connection in binary form.
  
13. Deserializing an Object
The opposite operation of the serialization is called deserialization i.e. to extracting the
data from a series of bytes is s known as deserialization
                                                            
14. Delete file or Directory
In this example we are discussing the deletion of a file or a directory by using a java
program. We pass the file name or the directory name to which we want to delete.
                                                           
15. Downloading and Viewing html source of a page i.e. running on the server
This section illustrates you the procedure of viewing complete html code of a page i.e.
running on the server.
         
16. URL file Download and Save in the Local Directory
This Program file download  from  URL and save this Url File in the specified directory.
This program specifies the directory path where the files to be stored  as first command
line argument and second command line arguments specifies URL File to be stored.
            
17. Create XML file from flat file and data insert into database
In this section, we have developed an application to create xml file from flat file and data
insert  into database in Java. 
                    
18. Miscellaneous 
o Compressing Streams
o Zip File
o Zip Folder
o Unzip File 
o Code for Garbage Collection
Introduction
The Java Input/Output (I/O) is a part of java.io package. The java.io package contains a
relatively large number of classes that support  input and output operations. The classes in the
package are primarily abstract classes and stream-oriented that define methods and subclasses
which allow bytes to be read from and written to files or other input and output sources. The
InputStream and OutputStream  are central classes in the package which are used for
reading from and writing to byte streams, respectively.
The java.io package can be categories along with its stream classes in a hierarchy structure
shown below:

InputStream:
The InputStream class is used for reading the data such as a byte and array of bytes from an
input source. An input source can be a file, a string, or memory that may contain the data. It
is an abstract class that defines the programming interface for all input streams that are
inherited from it. An input stream is automatically opened when you create it. You cans
explicitly close a stream with the close( ) method, or let it be closed implicitly when the object
is found as a garbage.
The subclasses inherited from the InputStream class can be seen in a hierarchy manner
shown below:

InputStream is inherited from the Object class. Each class of the InputStreams provided by the
java.io package is intended for a different purpose.
 
OutputStream:
The OutputStream class is a sibling to InputStream that is used for writing byte and array of
bytes to an output source. Similar to input sources, an output source can be anything such as a
file, a string, or memory containing the data. Like an input stream, an output stream is
automatically opened when you create it. You can explicitly close an output stream with the
close( ) method, or let it be closed implicitly when the object is garbage collected.
The classes inherited from the OutputStream class can be seen in a hierarchy structure shown
below:

OutputStream is also inherited from the Object class. Each class of the OutputStreams
provided by the java.io package is intended for a different purpose.
How Files and Streams Work:
Java uses streams to handle I/O operations through which the data is flowed from one
location to another. For example, an InputStream can flow the data from a disk file to the 
internal memory and an OutputStream can flow the data from the internal memory to a disk
file. The disk-file may be a text file or a binary file. When we work with a text file,  we use a
character stream where one character is treated as per byte on disk. When we work with a
binary file,  we use a binary stream.
The working process of the I/O streams can be shown in the given diagram.

Classes and Interfaces of the I/O Streams


Classes:
The following listing of classes are provided by the java.io package shown in the table:
 Class  Description
 BufferedInputStream It used for creating an internal
buffer array. It supports the mark
and reset methods.
 BufferedOutputStream This class used for writes byte to
output stream. It implements a
buffered output stream.
 BufferedReader This class provides read text from
character input stream and
buffering characters. It also reads
characters, arrays and lines.
 BufferedWriter This class provides write text from
character output stream and
buffering characters. It also writes
characters, arrays and lines.
 ByteArrayInputStream It contains the internal buffer and
read data from the stream.
 ByteArrayOutputStream This class used for data is written
into byte array. This is implement
in output stream class. 
 CharArrayReader It used for char input stream and
implements a character buffer.
 CharArrayWriter This class also implements a
character buffer and it uses an
writer.
 DataInputStream This class reads the primitive data
types from the input stream in a
machine format.
 DataOutputStream This class writes the primitive data
types from the output stream in
machine format.
 File This class shows a file and
directory pathnames.
 FileDescriptor This class uses for create a
FileInputStream and
FileOutputStream.
 FileInputStream It contains the input byte from a
file and implements an input
stream.
 FileOutputStream It uses for writing data to a file and
also implements an output stream.
 FilePermission It provides the permission to
access a file or directory.
 FileReader This class used for reading
characters file.
 FileWriter This class used for writing
characters files.
 FilterInputStream This class overrides all methods of
InputStream and contains some
other input stream.
 FilterOutputStream This class overrides all methods of
OutputStream and contains some
other output stream.
 FilterReader It reads the data from the filtered
character stream.
 FilterWriter It writes data from the filtered
character stream.
 InputStream This class represents an input
stream of bytes.
 InputStreamReader It reads bytes and decodes them
into characters.
 LineNumberReader This class has a line numbers
 ObjectInputStream This class used for recover the
object to serialize previously. 
 ObjectInputStream.GetField This class access to president
fields read form input stream.
 ObjectOutputStream This class used for write the
primitive data types and also write
the object to read by the
ObjectInputStream.
 ObjectOutputStream.GetFiel This class access to president
d fields write in to ObjectOutput.
 ObjectStreamClass Serialization's descriptor for
classes.
 ObjectStreamField This class describes the
serializable field.
 OutputStream This class represents an output
stream of bytes.
 OutputStreamWriter It writes bytes and decodes them
into characters.
 PipedInputStream In this class the data bytes are
written into piped output stream.
This class also connected into a
piped output stream.
 PipedOutputStream This class also communicates the
piped input stream into piped
output stream. It creates
communication between both.
 PipedReader It is a piped character-input
stream.
 PipedWriter It is a piped character-output
stream.
 PrintStream This class adds the functionality of
another output stream.
 PrintWriter This class adds the functionality of
another input stream.
 PushbackInputStream It also include the another function
of input stream. Such as: "push
back" or "unread" one byte.
 PushbackReader This is a character stream reader
and reads the data push back into
the stream.
 RandomAccessFile It supports both reading and
writing to a random access file.
 Reader It used for reading character
stream.
 SequenceInputStream It represents the logical
concatenation of other input
stream.
 SerializablePermission This is a serializable permission
class.
 StreamTokenizer It takes an input stream and parse
it into "tokens" . The token to be
allowed at the read time.
 StringReader This is a character string class. It
has character read source.
 StringWriter This is also a character string class.
It uses to shows the output in the
buffer.
 Writer It uses for writing to character
stream.
Interfaces:
The following summary of Interfaces provided by the java.io package shown in the table:
Interface  Description
 DataInput This interface can be used for reading
byte stream and reconstructing the java
primitive data types.
 DataOutput This interface can be used for writing the
byte stream and converting data from the
java primitive data types.
 Externalizable This is written in Serializable Stream. It
save and store it's contents.
 FileFilter It can be used for Filtering the Pathnames.
 FilenameFilter This interface used for Filter the
Filenames.
 ObjectInput This interface used for reading of objects
and it extends the DataInput interface. 
 ObjectInputValidation This is a Callback interface. It allows the
validation of objects within a graph.
 ObjectOutput This interface used for writing of objects
and it extends the DataOutput interface.
    
This interface used for Constants writing
ObjectStreamConstant
into Serialization Objects Stream.
s
 Serializable This interface implementing in the
java.io.Serializable interface.
Exceptions Classes:
The following summary of the exception classes provided by the java.io package shown in
the table:
Exceptions   Description
CharConversionException It provides detail message in the
catch block to associated with
the CharConversionException
EOFException This exception indicates the end
of file. When the file input
stream to be end then
EOFException to be occuted.
FileNotFoundException When the open file's pathname
does not find then this exception
to be occured.
InterruptedIOException When the I/O operations to
interrupted from any causes then
it becomes.
InvalidClassException Any problems to be created with
class, when the Serializing
runtime to be detected. 
InvalidObjectException When the de-serialized  objects
failed then it occurs.
IOException When the I/O operations to be
failed then it occurs.
NotActiveException The Serialization or
deserialization operations are not
active then it occurs.
NotSerializableException This exception when the instance
is required to a Serializable
interface.
ObjectStreamException This is a supper class of all
exception class. It used for
specific to Object Stream
Classes.
OptionalDataException When the reading data
operations to failed then it these
exception occurs. It is belonging
to the serialized object
StreamCorruptedException It thrown when the control
information that was read form
an object stream vioaltes internal
consistency checks.
SyncFaieldException The sync operation is failed then
SyncFaieldException to be
occure.
UnsupportedEncodingExceptio The Character Encoding is not
n supported.
UTFDataFormatException A molformed UTF-8 has been
read in a data input stream, it
implemented by data input
interface.
WriteAbortedException In this exception to be thrown by
the ObjectStreamException
during a write operating.
Reading Text from the Standard Input

Standard Streams:
Standard Streams are a feature provided by many operating systems. By default, they read
input from the keyboard and write output to the display. They also support I/O operations on
files.
 Java also supports three Standard Streams:
 Standard Input: Accessed through System.in which is
used to read input from the keyboard.
 Standard Output: Accessed through System.out  which
is used to write output to be display.
 Standard Error: Accessed through System.err which is
used to write error output to be display.

These objects are defined automatically and do not need to be opened explicitly. Standard
Output and Standard Error, both are to write output; having error output separately so that
the user may read error messages efficiently.
System.in is a byte stream that has no character stream features. To use Standard Input as a
character stream, wrap System.in within the InputStreamReader as an argument.
InputStreamReader inp = new InputStreamReader(system.in);
Working with Reader classes:
Java provides the standard I/O facilities for reading text from either the file or the keyboard on
the command line. The Reader class is used for this purpose that is available in the java.io
package. It acts as an abstract class for reading character streams. The only methods that a
subclass must implement are read(char[], int, int) and close(). the Reader class is further
categorized into the subclasses. 
The following diagram shows a class-hierarchy of the java.io.Reader class.
However, most subclasses override some of the methods in order to provide higher efficiency,
additional functionality, or both.
InputStreamReader:
An InputStreamReader is a bridge from byte streams to character streams i.e. it reads bytes
and decodes them into Unicode characters according to a particular platform. Thus, this class
reads characters from a byte input stream. When you create an InputStreamReader, you
specify an InputStream from which, the InputStreamReader reads the bytes.
The syntax of InputStreamReader is written as:
InputStreamReader <variable_name> = new InputStreamReader(system.in)
BufferedReader : 
The BufferedReader class is the subclass of the Reader class. It reads character-input stream
data from a memory area known as a buffer maintains state.  The buffer size may be
specified, or the default size may be used that is large enough for text reading purposes. 
BufferedReader converts an unbuffered stream into a buffered stream using the wrapping
expression, where the unbuffered stream object is passed to the constructor for a buffered
stream class.
For example the constructors of the BufferedReader class shown as:
BufferedReader(Reader in):Creates a buffering character-input
stream that uses a default-sized input buffer.
BufferedReader(Reader in, int sz): Creates a buffering character-
input stream that uses an input buffer of the specified size.

BufferedReader class provides some standard methods to perform specific reading operations
shown in the table. All methods throws an  IOException, if an I/O error occurs.
 Return
 Method  Description
Type
 read( )  int  Reads a single character 
 read(char[] cbuf,  Read characters into a portion of
 int
int off, int len) an array.
 Read a line of text. A line is
 readLine( )  String considered to be  terminated by
('\n').
  close( )  void   Closes the opened stream.
  This program illustrates you how to use standard input stream to read the user input..
import java.io.*;
 
public class ReadStandardIO{
 
  public static void main(String[] args) throws IOException{

      InputStreamReader inp = new InputStreamReader(System.in)


      BufferedReader br = new BufferedReader(inp);

      System.out.println("Enter text : ");
 
     String str = in.readLine();

     System.out.println("You entered String : ");

      System.out.println(str);
  }
}

 
Output of the Program:
C:\nisha>javac
ReadStandardIO.java

C:\nisha>java
ReadStandardIO
Enter text :
this is an Input Stream
You entered String :
this is an Input Stream

C:\nisha>
Download this example

Working With File

In the previous chapter, we learned how to work with the streams. which provide a simple
model for reading and writing data. However, streams don't support all the operations that are
common with a disk file. In lesson, we will learn how to work with a file using the non-stream
file I/O.
The File class deals with the machine dependent files in a machine-independent manner i.e. it
is easier to write platform-independent code that examines and manipulates files using the File
class. This class is available in the java.lang package.
The java.io.File is the central class that works with files and directories. The instance of
this class represents the name of a file or directory on the host file system. 
When a File object is created, the system doesn't check to the existence of a corresponding
file/directory. If the file exist, a program can examine its attributes and perform various
operations on the file, such as renaming it, deleting it, reading from or writing to it.
The constructors of the File class are shown in the table:
 Constructor  Description
 Create File object for default
 File(path) directory (usually where program is
located).
 File(dirpath,fname  Create File object for directory path
) given as string.
 File(dir, fname)  Create File object for directory.
Thus the statement can be written as:
File f = new File("<filename>");

The methods that are used with the file object to get the attribute of a corresponding file
shown in the table.
 Method  Description
 f.exists()  Returns true if file exists.
 f.isFile()  Returns true if this is a normal file.
 f.isDirectory()  true if "f" is a directory.
 f.getName()  Returns name of the file or directory.
 f.isHidden()  Returns true if file is hidden.
 f.lastModified()  Returns time of last modification.
 f.length()  Returns number of bytes in file.
 f.getPath()  path name.
 f.delete()  Deletes the file.
 Renames f to File f2. Returns true if
 f.renameTo(f2)
successful.
 f.createNewFile(  Creates a file and may throw
) IOException. 

Create a File 

Introduction
Whenever the data is need to be stored, a file is used to store the data. File is a collection of
stored information that are arranged in string, rows, columns and lines etc.
In this section, we will see how to create a file. This example takes the file name and text data
for storing to the file.
For creating a new file File.createNewFile( ) method is used. This method returns a boolean
value true if the file is created otherwise return false. If the mentioned file for the specified
directory is already exist then the createNewFile() method returns the false otherwise the
method creates the mentioned file and return true. 
Lets see an example that checks the existence of  a specified file.
import java.io.*;

public class CreateFile1{
    public static void main(String[] args) throws IOException{
      File f;
      f=new File("myfile.txt");
      if(!f.exists()){
      f.createNewFile();
      System.out.println("New file \"myfile.txt\" has been created 
                          to the current directory");
      }
    }
}

First, this program checks, the specified file "myfile.txt" is exist or not. if it does not exist
then a new file is created with same name to the current location. 
Output of the Program

C:\nisha>javac CreateFile1.java

C:\nisha>java CreateFile1
New file "myfile.txt" has been created
to the current directory

C:\nisha>
If you try to run this program again then after checking the existence of the file, it will not be
created and you will see a message as shown in the output.
C:\nisha>javac CreateFile1.java

C:\nisha>java CreateFile1
The specified file is already exist

C:\nisha>
Constructing a File Name path 
In Java, it is possible to set dynamic path, which is helpful for mapping local  file name with
the actual path of the file using the constructing filename path technique.
As you have seen, how a file is created to the current directory where the program is run. Now
we will see how the same program constructs a File object from a more complicated file
name, using the static constant File.separator or File.separatorCharto specify the file name
in a platform-independent way. If we are using Windows platform then the value of this
separator is  ' \ ' .
Lets see an example to create a file to the specified location.

import java.io.*;

public class PathFile{
    public static void main(String[] args) throws IOExce
ption{
      File f;
    f=new File("example" + File.separator + "myfile.txt"
);
      f.createNewFile();
      System.out.println("New file \"myfile.txt\" 
has been created 
                            
to the specified location");
      System.out.println("The absolute path of the file 
is: "
                +f.getAbsolutePath());      
    }
}

Output of the program:


C:\nisha>javac PathFile.java

C:\nisha>java PathFile
New file "myfile.txt" has been created to
the specified location
The absolute path of the file is:
C:\nisha\example\myfile.txt
C:\nisha>
Download this Program
Another program set the dynamic path using File.separator given below:
import java.io.*;
 
public class ConstructingFileNamePath {
 
  public static void main(String[] args){

      String filepath = File.separatorChar + "tapan"
              + File.separatorChar + "joshi";

      System.out.println("The path of the file is  :  " 
              + filepath);
 
       }
 
}

Output of the program:


C:\java>java
ConstructingFileNamePath
The path of the file is :
\tapan\joshi
Download this example.

Java read file line by line - Java Tutorial


Introduction
Lets understand some I/O streams that are used to perform reading and writing operation in a
file. In the section of Java Tutorial you will learn how to write java program to read file line
by line. 
Java supports the following I/O file streams.

 FileInputstream
 FileOutputStream 

FileInputstream:
This class is a subclass of Inputstream class that reads bytes from a specified file name . The
read() method of this class reads a byte or array of bytes from the file. It returns -1 when the
end-of-file has been reached. We typically use this class in conjunction with a
BufferedInputStream and DataInputstream class to read binary data. To read text data,
this class is used with an InputStreamReader and BufferedReader class. This class throws
FileNotFoundException, if the specified file is not exist. You can use the constructor of this
stream as:
FileInputstream(File filename);
FileOutputStream:
This class is a subclass of OutputStream that writes data to a specified file name. The
write() method of this class writes a byte or array of bytes to the file. We typically use this
class in conjunction with a BufferedOutputStream and a DataOutputStream class to
write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and
an OutputStreamWriter class. You can use the constructor of this stream as:
FileOutputstream(File filename);
 DataInputStream:
This class is a type of FilterInputStream that allows you to read binary data of Java
primitive data types in a portable way. In other words, the DataInputStream class is used to
read binary Java primitive data types in a machine-independent way. An application uses a
DataOutputStream to write data that can later be read by a DataInputStream. You can use
the constructor of this stream as:
DataInputStream(FileOutputstream finp);
The following program demonstrate, how the contains are read from a file.
import java.io.*;

public class ReadFile{
    public static void main(String[] args) throws IOException{
      File f;
    f=new File("myfile.txt");

      if(!f.exists()&& f.length()<0)
      System.out.println("The specified file is not exist");

      else{
         FileInputStream finp=new FileInputStream(f);
      byte b;
    do{
      b=(byte)finp.read();
      System.out.print((char)b);
    }
      while(b!=-1);
        finp.close();
        }
    }
  }

Output of the Program:


C:\nisha>javac
ReadFile.java

C:\nisha>java ReadFile
This is a text file?
C:\nisha>
This program reads the bytes from file and display it to the user.
Download this Program
The another program  use DataInputStreams for reading textual input line by line with an
appropriate BufferedReader.
import java.io.*;
class FileRead 
{
   public static void main(String args[])
  {
      try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Output of the Program:


C:\nisha>javac
FileRead.java 
C:\nisha>java FileRead
this is a file

C:\nisha>

Download the code

Java Write To File - Java Tutorial


Introduction
In the section, you will learn how to write data to a file. As we have discussed, the
FileOutputStream class is used to write data to a file. 
Lets see an example that writes the data to a file converting into the bytes.
This program first check the existence of the specified file. If the file exist, the data is written
to the file through the object 
of the FileOutputStream class. 
 
 
import java.io.*;

public class WriteFile{

    public static void main(String[] args) throws IOException{

      File f=new File("textfile1.txt");
      FileOutputStream fop=new FileOutputStream(f);

      if(f.exists()){
      String str="This data is written through the program";
          fop.write(str.getBytes());

          fop.flush();
          fop.close();
          System.out.println("The data has been written");
          }

          else
            System.out.println("This file is not exist");
    }
  }

Output of the Program 


C:\nisha>javac WriteFile.java

C:\nisha>java WriteFile
The data has been written
C:\nisha>

Download this Program


The another way for writing data to a file, the class FileWriter and BufferedWriter are used.
 FileWriter :
 FileWriter is a subclass of OutputStreamWriter class that is used to write text (as opposed
to binary data) to a file. You create a FileWriter by specifying the file to be written to, or
optionally, when the data should be appended to the end of an existing file instead of
overwriting that file. The FileWriter class creates an internal FileOutputStream to write
bytes to the specified file
BufferedWriter :
The BufferedWriter class is used to write text to a character-output stream, buffering
characters so as to provide for the efficient writing of single characters, arrays and strings. 
The constructor of the FileWriter class takes the file name which has to be buffered by the
BufferedWriter stream. The write( ) method of BufferedWriter class is used to create the file
into specified directory.
Following code  write data into new file: 
out.write(read_the_Buffered_file_name);
Following code creates the object of FileWriter and BufferedWriter: 
FileWriter fstream = new FileW
riter(file_name);
BufferedWriter out = new Buffe
redWriter(fstream);
Lets see an another example that writes the text input by the user using the FileWriter and the
BufferedWriter class.
import java.io.*;

public class FileWriter{

  public static void main(String[] args) throws IOException{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter the file name to create : ");
    String file_name = in.readLine();
    File file = new File(file_name);
    boolean exist = file.createNewFile();
    if (!exist)
    {
      System.out.println("File already exists.");
      System.exit(0);
    }
    else
    {
      FileWriter fstream = new FileWriter(file_name);
      BufferedWriter out = new BufferedWriter(fstream);
      out.write(in.readLine());
      out.close();
      System.out.println("File created successfully.");
    }
  }
}

Output of the Program 


C:\nisha>javac CreateFile.java

C:\nisha>java CreateFile
Please enter the file name to
create : nishu.txt
this is my name
File created successfully.

C:\nisha>
 Download the code

Append To File - Java Tutorial


introduction
In the section, you will learn how the data is appended to an existing file. We will use the class
FileWriter and BufferedWriter to append the data to a file.
 FileWriter
The FileWriter is a class used for writing character files. The constructors of this class assume
that the default character encoding and the default byte-buffer size are acceptable. This
constructor simply overwrite the contents in the file by the specified string but if you put the
boolean value as true with the file name (argument of the constructor) then the constructor
append the specified data to the file i.e. the pre-exist data in a file is not overwritten and the
new data is appended after the pre-exist data.

BufferedWriter
The BufferWriter class is used to write text to a character-output stream, buffering characters
so as to provide for the efficient writing of single characters, arrays, and strings.

Here is the code of java program to write text to a file:


import java.io.*;
class FileWrite 
{
   public static void main(String args[])
  {
      try{
    // Create file 
    FileWriter fstream = new FileWriter("out.txt",true);
        BufferedWriter out = new BufferedWriter(fstream);
    out.write("Hello Java");
    //Close the output stream
    out.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}
Download the code

Getting the Size of a File in Java


Introduction
In this section you will learn how to get the size (in bytes) of a specified file. you will also
learn about the methods that can be used to get the file size. If you give the text based file then
the program tells you the number of characters otherwise it will give you the file size in bytes.
Program takes the file name through the keyboard and checks whether the file exists. If the file
exists then the length( ) method of the instance of the File class gives you size of the file.
Here is the code of the program : 
import java.io.*;

  public class FileSize{
 
 public static void main(String[] args) throws IOException{
 
   System.out.print("Enter file name : ");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in))
;
    File f = new File(in.readLine());
  
  if(f.exists()){
   
   long file_size = f.length();
 
      System.out.println("Size of the file : " + file_size);
 
   }
    
else{
   
   System.out.println("File does not exists.");
 
     System.exit(0);
   
 }
 
 }
 
}

Output of the Program:


C:\nisha>java
FileSize
Enter file name :
myfile.txt
Size of the file :
19

C:\nisha>

Download this example.

Count lines of a particular file

In this section, you will learn how to count the availability of  text lines in the particular file. A
file is read before counting lines of a particular file,  . File is a collection of stored information
that are arranged in string, rows, columns and lines etc. Try it for getting the lines through the
following program.
Description of program:
The following program helps you in counting lines of a particular file. At the execution time
of this program, it takes a file name with its extension from a particular directory and checks it
using the exists() method. If the file exists, it will count lines of a particular file otherwise it
will display a message "File does not exists!". 
Description of code:
FileReader(File file):
This is the constructor of FileReader class that is reliable for reading a character files. It
constructs a new FileReader and takes a file name that have to be read. 
FileNumberReader():
This is the constructor of FileNumberReader class. It constructs a new line-numbering
reader. It  reads characters and puts into buffer. By default the numbering of line begins from
'0'. 
Here is the code of program:
import java.io.*;

  public class NumberOfLine{
  public static void main(String[] args) {
 
    try{

      System.out.println("Getting line number of a paritcular file example!"
);
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in
));
      System.out.println("Please enter file name with extension:");
      
      String str = bf.readLine();
 
      File file = new File(str);

      if (file.exists()){

        FileReader fr = new FileReader(file);
   
     LineNumberReader ln = new LineNumberReader(fr);
  
      int count = 0;
 
        while (ln.readLine() != null){
 
          count++;
     
   }
 
       System.out.println("Total line no: " + count);
 
        ln.close();
 
      }
 
      else{
 
       System.out.println("File does not exists!");
 
     }
 
    }

    catch(IOException e){

      e.printStackTrace();

    }

  }

Output of program:
C:\vinod\Math_package>javac
NumberOfLine.java

C:\vinod\Math_package>java
NumberOfLine
Getting line number of a paritcular
file example!
Please enter file name with
extension:
AddTwoBigNumbers.shtml
Total line no: 58

Change a file timestamp 


Timestamp is a utility to change or  modify the time of a file. Java provides the facility for
changing a file timestamp according to the  user reliability.  
Description of program:
This program helps you in changing a file timestamp or modification time in Java. After
running this program it will take a file name and its modification date in 'dd-mm-yyyy'
format. Then it will check the given file is exist or not using the exists() method. When the file
exists, this program will change the date of given file and it will display a message
"Modification is successfully!" otherwise it will show "File does not exists!".
Description of code:
setLastModified(long time):
This is the method that sets the last modification time of a file or directory and returns
Boolean types values either 'true' or 'false'. If it will  return a 'true' only when the modification
is completely successfully otherwise, it will return 'false'. This method takes following long
type data:
        time: This is the time that have to be modified or set. 
getTime():
This is the method that returns the number of milliseconds in GMT format like: 23-04-2007.
Here is the code of program:
import java.io.*;
import java.util.*;

import java.text.*;

public class ChangeFileDate{
 
  public static void main(String[] args) {
 
    try{
 
     System.out.println("Change file timestamp example!");
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.println("Enter file name with extension:");
 
      String str = bf.readLine();
      System.out.println("Enter last modified date in 'dd-mm-yyyy' format:");
      String strDate = bf.readLine();
 
     SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy");
 
     Date date = sdf.parse(strDate);
  
    File file = new File(str);
 
      if (file.exists()){

        file.setLastModified(date.getTime());
 
       System.out.println("Modification is successfully!");
   
   }

      else{

        System.out.println("File does not exists!");

      }
   
 }

    catch(Exception e){
 
     e.printStackTrace();

    }
  
}

Output of program:
C:\vinod\Math_package>javac
ChangeFileDate.java

C:\vinod\Math_package>java
ChangeFileDate
Change file timestamp example!
Enter file name with extension:
StrStartWith.shtml
Enter last modified date in 'dd-mm-
yyyy' format:
23-04-2007
Modification is successfully!

Create Temp File


In this section, you will learn how a temporary file is created to the default directory. 
A temporary file is a file that is created to store information temporarily so that the memory
can be freed for other purposes. It is beneficial and secure to prevent loss of data when a
program performs certain functions. For example, an application "Word" automatically
determines where and when temporary files are to be created. The temporary files only exist
during the current session of an application

as the name suggest "temp".  When the application is shut down, all temporary files are first
closed and then deleted.
Description of program:

The following code of program will help you in creating a Temporary File to your default
directory. Here we have created a temporary file object. Then we have used a method to get
the entire path of the temp file which gets created. The method is
tempFile.getAbsolutePath();. We have also used a try and catch block here to catch the
exception on occurrence. And if the file could not be created then we will get a message that
"temp file not created".
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class CTFile {
  public static void main(String[] args){
    File tempFile = null;
    
    try {
      tempFile = File.createTempFile("MyFile.txt", ".tmp"
      System.out.print("Created temporary file with name
      System.out.println(tempFile.getAbsolutePath());
      } catch (IOException ex) {

      System.err.println("Cannot create temp file: " 
      } finally {
        if (tempFile != null) {
        }
      }
    }
}

Output of the program:


C:\unique>javac CTFile.java

C:\unique>java CTFile
Created temporary file with name
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\MyFile.txt49
754.tmp

C:\unique>
Download this example.
 

Delete temp file


                          
In this section, you will learn how a temporary  file is deleted from the current working
directory. Java provides deleteOnExit() method for deleting a temporary file. 
Description of program:
This program deletes a temp file from the current working directory which is created for the
current session. This program takes a file name that have ".temp" extension and checks it
through the exists() method whether it does exist or not. When the file is exist, it will delete
the specified file using the deleteOnExit() method and display a message " file is deleted!";
Otherwise  it will show a message "File does not exists!". 
Description of code:
deleteOnExit( ):
This is the method that is used to delete a file which have to be deleted and terminates the
virtual machine. The deletion process is completely successfully only the normal termination
of the virtual machine that is defined by the Java Language Specification ( JLS ).
Here is the code of program:
import java.io.*;
 
public class DeleteTempFile{
 
 public static void main(String[] args) {
 
   try{
  
    System.out.println("Delete temp file example!");
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in
));
      System.out.println("Please enter file name that has '.temp' extension:
");
      String str = bf.readLine();
  
    File file = new File(str+".temp");
 
     if (file.exists()){
 
       file.deleteOnExit();
  
      System.out.println("file is deleted!");
 
      }
     
 else{
    
    System.out.println("File does not exists!");
  
    }
   
 }
  
  catch(IOException e){
 
      e.printStackTrace();
   
 }
 
 }
 
}

Output of program:
C:\vinod\Math_package>javac
DeleteTempFile.java

C:\vinod\Math_package>java
DeleteTempFile
Delete temp file example!
Please enter file name that has
'.temp' extension:
rose
file is deleted!
Download this Program:

Getting a absolute path


                          
To find a file or directory it is very necessary to know the path of the file or directory so that
you can access it. If you know the path then it is very easy to work on it. Suppose a situation
where a problem comes in front you where you don't know the path of the file, then what will
you do. Then this problem can be solved by using a method getAbsolutePath().The method
getAbsolutePath() should be used where we don't know the exact path of the file.
To find an absolute path of a file, Firstly we have to make a class GetAbsolutePath. Inside
this class define the main method. Inside this method  define a File class of java.io package.
Inside the constructor of a File class pass the name of the file whose absolute path you want to
know. Now call the method getAbsolutePath() of the File class by the reference of  File class
and store it in a String variable. Now print the string, you will get a absolute path of the file.
In this class we have make use of the following things by which this problem can be solved.
File: It is class in java.io package. It implements Comparable and Serializable interface.
getAbsolutePath():  It returns the absolute path name in  the form of string.
Code of the program is given below:
import java.io.*;

  public class  GetAbsolutePath{
 
 public static void main(String[] 
args){
 
   String str = args[0];

      File file = new File(str);
    String absolutePathOfFirstFile 
= file.getAbsolutePath();

    System.out.println(" The absol
ute path in first form is " 
                         
+ absolutePathOfFirstFile);

 
file = new File( "chandan" + File.
separatorChar+ str);
    String absolutePathOfSecondFil
e = file.getAbsolutePath();
    System.out.println(" The absol
ute path is " + absolutePathOfSeco
ndFile);

 
file = new File("chandan" + File.s
eparator + ".." + File.separator + 
str);
    String absolutePathOfThirdFile 
= file.getAbsolutePath();
    System.out.println(" The absol
ute path is " + absolutePathOfThir
dFile); 

    }
 
}

Output of the program 


C:\java>java GetAbsolutePath
chandan
The absolute path in first form is
C:\tapan\chandan
The absolute path is
C:\tapan\chandan\chandan
The absolute path is
C:\tapan\chandan\..\chandan
Download this example.
Getting the Parents of a Filename
Program uses getParent( ) method of the File class object to find the parent directory name of
the current directory. For example,
System.getProperty("user.dir"):
This method returns the user's current directory. The getProperty() method is the system
method which is imported from the System class of the java.lang.*; package. This method
tells about the system property according to the indicating argument. Here, the indicating
argument user.dir indicates about the current directory.
Here is the code of the program : 
import java.io.*;

  public class  GetParentDir{
 
 private static void dirlist(String fname){

    File dir = new File(fname);
    String parentpath = dir.getParent();
  
  System.out.println("Current Directory : "+ dir);

    System.out.println("parent Directory : "+ parentpath);
 
 }

 
  public static void main(String[] args){
 
   String currentdir = System.getProperty("user.dir");

    dirlist(currentdir);
 
 }

Output of the program 


C:\nisha>javac
GetParentDir.java

C:\nisha>java
GetParentDir
Current Directory :
C:\nisha
parent Directory : C:\

C:\nisha>
Download this example.

5. Working with a Directory


In the section, you will learn how a directory is created. Apart from this, you will also
be aware from some manipulations that are performed 
on a directory.

o Creating a Directory
o Copying a Directory or file
o Traversing files and directories
o Getting the Current Working Directory
o Getting the Modification Time of a File or Directory
o Listing Files or Subdirectories 
o Deleting a File
Creating a Directory
Introduction
In the section, you will learn how a directory or subdirectories are created. This program also
explains the process of creating all non-existent ancestor directories automatically. We will
use the File class to crate the directory.
 File
The File class an abstract representation of file and directory pathnames. File class is used to
interact with the files system.

Here is the code for creating directory and all non-existing ancestor directories:
import java.io.*;
class CreateDirectory 
{
   public static void main(String args[])
  {
      try{
    String strDirectoy ="test";
    String strManyDirectories="dir1/dir2/dir3";

    // Create one directory
    boolean success = (new File(strDirectoy)).mkdir();
    if (success) {
      System.out.println("Directory: " + strDirectoy + " created");
    }    
  
    // Create multiple directories
    success = (new File(strManyDirectories)).mkdirs();
    if (success) {
      System.out.println("Directories: " + strManyDirectories + " created");
    }

    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Output of the program: 


C:\nisha>javac
CreateDirectory.java

C:\nisha>java
CreateDirectory
Directory: test created
Directories:
dir1/dir2/dir3 created

C:\nisha>
This program takes inputs to create a directory "test" and subdirectories "dir1\dir2\dir3". the
mkdir( ) method is used to create a single directory while the mkdirs( ) method is used to
create multiple subdirectories.
Download the code

Copying a Directory or file


Introduction
Java has the features of the copying the directory and it's contents. This example shows how to
copy the directory and files into a new directory.
In this program, you will see how contains of a directory or a file is copied  from the specified
source directory (subdirectories and files) to specified destination directory. If you specify the
unknown source directory which does not exist then the program gives the output message like
: File or directory does not exist. otherwise read the source directory name and create the
OutputStream instance for the destination directory while if you specify the unknown
destination directory name then the program creates new directory with that name for the
destination directory where the contents of the source directory have to be copied.
In this program, there are two methods have been used to complete the program. These
methods are explained ahead : 
copyDirectory (File srcPath, File dstPath):

The copyDirectory() method is used to copy contents from the specified source directory to
the specified destination directory. This method takes two File type arguments passed by the
calling method in the main method and check whether the specified directory is a directory
exactly or not. If the specified name is in the exact directory format and that exists then the
method generates the list of all the sub directories and file inside the source directory using the
list() method and copy one by one to the destination directory otherwise the specified name is
copies (treated) as a file name directly.
And another method is the main method in which the program read the source and destination
directory or file name.
Here is the code of the program : 
import java.io.*;
  public class CopyDirectory{
 
 public static void main(String[] args) throws IOException{
 
   CopyDirectory cd = new CopyDirectory();
    BufferedReader in = new BufferedReader
                        (new InputStreamReader(System.in));
    System.out.println("Enter the source directory or file name : ");

      String source = in.readLine();

    File src = new File(source);
 
    System.out.println("Enter the destination 
                 directory or file name : ");
    String destination = in.readLine();
  
      File dst = new File(destination); 

    cd.copyDirectory(src, dst);

  }
  

  public void copyDirectory(File srcPath, File dstPath)
                               throws IOException{
  
  if (srcPath.isDirectory()){

      if (!dstPath.exists()){

        dstPath.mkdir();
 
     }

 
     String files[] = srcPath.list();
  
    for(int i = 0; i < files.length; i++){
        copyDirectory(new File(srcPath, files[i]), 
                     new File(dstPath, files[i]));
 
      }

    }
 
   else{
 
      if(!srcPath.exists()){

        System.out.println("File or directory does not exist.");
 
       System.exit(0);

      }
      
else
 
      {
 
       InputStream in = new FileInputStream(srcPath);
       OutputStream out = new FileOutputStream(dstPath); 
                     // Transfer bytes from in to out
            byte[] buf = new byte[1024];
 
              int len;
 
           while ((len = in.read(buf)) > 0) {
 
          out.write(buf, 0, len);

        }
 
       in.close();
 
           out.close();

      }
 
   }
   
 System.out.println("Directory copied.");
 
 }

Output of the Program:


C:\nisha>java CopyDirectory
Enter the source directory or file name :test
Enter the destination directory or file name :dir1
Directory copied.
Download this example.

Traversing files and directories

This section you will learn how the files and subdirectories are traversed lying under a
directory. We can find that, how many files and directories are available within a directory.
This is very frequently used where lot of work depends on the files and directories. .
The given program describes how you can traverse a directory if it contains directory and files
under it. If the directory contains no files and directory then it will tell you that the directory
contains no directory and files in it, if it contains a directory and files in it then it will display
all the files and directories.
To implement this program, first make a class named as TraversingFileAndDirectories then
make an object of File class and pass any directory and filename to its constructor. After that,
check it whether the file or directory you have entered is a directory or a file. If it is a directory
then it will display that it is a directory otherwise not a directory. If it is a directory, it checks
whether it contains more directory and files in it. If it contains then it will display you the list
of the files and directories.
Code of the program is given below
import java.io.*;

 
public class TraversingFileAndDirectories{
 
 public static void main(String args[]){
  
  String dirname = args[0];
 
    File file = new File(dirname); 
 
        if(file.isDirectory()){
 
      System.out.println("Directory is  " + dirname);
   
   String str[] = file.list();
 
      for( int i = 0; i<str.length; i++){
  
      File f=new File(dirname + " / " + str[i]);
  
      if(f.isDirectory()){
   
       System.out.println(str[i] + " is a directory");
 
        }
 
       else{
 
         System.out.println(str[i] + " is a file");
 
        }
 
      }
 
    }
  
  else{
  
      System.out.println(dirname  + " is not a directory");
 
    }

  }
}

Output of the program 

C:\java>java
TraversingFileAndDirectories
chandan
Directory is chandan
ConstructingFileNamePath.java is a
file
constructingfilenamepath.shtml is a
file
EnterValuesFromKeyboard.java is a
file
entervaluesfromkeyboard.shtml is a
file
Factorial.java is a file
factorial.shtml is a file
UseOfThisOperator.java is a file
useofthisoperator.shtml is a file
Download this program

Getting the Current Working Directory


Introduction
In this section, you will learn how to get the current working directory. The current working
directory that means where your program run. This program shows the current directory name
when your program run. Following methods are invoked for this purpose : 
System.getProperty("user.dir");

This is the getProperty() method of the System class of the java.lang package returns the
system properties according to the indicated argument. Here, the mentioned indicated
argument is "user.dir" which indicates about the getting the current directory name.
Here is the code of the program :
import java.io.*;
 
public class  GetCurrentDir{
 
  private static void dirlist(String fname){
 
   File dir = new File(fname);
  
  System.out.println("Current Working Directory : "+ dir);
 
  }

 
 public static void main(String[] args){
 
    String currentdir = System.getProperty("user.dir");
 
    dirlist(currentdir);
 
 }
 
}

Output of the program 

C:\nisha>javac
GetCurrentDir.java

C:\nisha>java
GetCurrentDir
Current Working
Directory : C:\nisha

C:\nisha>
Download this example.

Getting the Modification Time of a File or


Directory
Introduction
In this section, you will learn how to get the last modification date and time of any file or a
folder.
The file name or the directory name is taken by the user to get the last modification date and
time of the specified file or a folder. This program checks whether the specified file or the
folder exists or not.
If the file or the folder exists then the method lastModified( ) gives you the last modification
date and time of the specified file or folder name. This method shows the time in millisecond.
The getName( ) method retrieves the name of the file or directory.
Here is the code of the program : 
import java.io.*;
 
import java.util.*;
 
public class GetDirectoryAndFileModifiedTime{
 
  public static void main(String[] args) throws IOException{
    BufferedReader in = new BufferedReader(new 
                          InputStreamReader(System.in));
    System.out.println("Enter file or directory name in proper 
                        format to get the modification date and time : ");
    File filename = new File(in.readLine());
 
    if (filename.isDirectory()){
 
      if (filename.exists()){
 
       long t = filename.lastModified();
 
       System.out.println("Directory name : " + filename.getName());
        System.out.println("Directory 
                modification date and time : " + new Date(t)); 
     }
   
   else{
    
    System.out.println("Directory not found!");
 
        System.exit(0);
    
  }
   
 }
  
  else{
 
      if (filename.exists()){
 
       long t = filename.lastModified();
  
      System.out.println("File name : " + filename.getName());
        System.out.println("File 
                    modification date and time : " + new Date(t));
 
     }
  else{
    
    System.out.println("File not found!");
 
       System.exit(0);
   
   }
   
 }
  
}
 
}

Output of the Program:


C:\nisha>java GetDirectoryAndFileModifiedTime
Enter file or directory name in proper format to get
the modification date and time :
myfile.txt
File name : myfile.txt
File modification date and time : Thu Oct 04 16:31:39
GMT+05:30 2007

C:\nisha>
Download this example.

Listing Files or Subdirectories 


Introduction
This example illustrates how to list files and folders present in the specified directory. This
topic is related to the I/O (input/output) of java.io package.
In this example we are using File class of java.io package. The File class is an abstract
representation of file and directory pathnames. This class is an abstract, system-independent
view of hierarchical pathnames. An abstract pathname has two components:

1. An optional system-dependent prefix string,


such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Win32 UNC
pathname, and
2. A sequence of zero or more string names.

Explanation
This program list the file of the specified directory. We will be declaring a function called
dirlist which lists the contents present in the specified directory.
dirlist(String fname)
The function dirlist(String fname) takes directory name as parameter. The function creates a
new File instance for the directory name passed as parameter
File dir = new File(fname); 
and retrieves the list of all the files and folders present in the directory by calling list() method
on it. 
String[] chld = dir.list();  
Then it prints the name of files and folders present in the directory.
Code of the Program : 
import java.io.*;

public class  DirListing{
  private static void dirlist(String fname){
    File dir = new File(fname);
    String[] chld = dir.list();
    if(chld == null){
      System.out.println("Specified directory does not exist or is not a direc
tory.");
      System.exit(0);
    }else{
      for(int i = 0; i < chld.length; i++){
        String fileName = chld[i];
        System.out.println(fileName);
      }
    }
  }
  public static void main(String[] args){
    switch(args.length){
      case 0: System.out.println("Directory has not mentioned.");
          System.exit(0);
      case 1: dirlist(args[0]);
          System.exit(0);
      default : System.out.println("Multiple files are not allow.");
            System.exit(0);
    }
  }
}

Output of the Program:


C:\nisha>java
DirListing example
myfile.txt

C:\nisha>
At the time of execution, we have specified a directory name "example" that contains only a
single file "myfile.txt".
Download this example Example

Deleting a File
In this section, you will learn how a specified file or directory is deleted. For deleting a file
from a directory you need to give the file name to be deleted.
Description of program:

The following code of program deletes a file from a directory. In this program the compiler
will ask to enter the name of the file to be deleted. For this we have used
"BufferedReader(new InputStreamReader(System.in));" method as you very well know
about it. If the file exists in the directory then it will be deleted otherwise we will get a
message that "file was not successfully deleted".
import java.io.File;
import java.io.*;

public class DeletingFile {
  public static void main(String args[])throws IOException{
  BufferedReader in = new BufferedReader(new InputStreamReader(
    System.out.print("Enter the file name to delete:");
    String file_name = in.readLine();
    File file = new File("File already exist!");
    boolean exist = file.createNewFile();
     if (!exist){
     System.out.println("File was successfully deleted.\n");
     } else {
     System.out.println("File was not successfully deleted.\n"
     }
   }
}
        

Output of the program:


C:\unique>javac DeletingFile.java

C:\unique>java DeletingFile
Enter the file name to delete:wonderful.txt
File was successfully deleted.

C:\unique>
Download this example.
Filter I/O Streams
Like I/O streams, Filter streams are also used to manipulate the data reading from an underlying
stream.. Apart from this, it allows the user to make a chain using multiple input stream so that, the
operations that are to be applied on this chain, may create a combine effects on several filters. 

Introduction 

Introduction:
As mentioned earlier, The InputStream and OutputStream  classes are used for reading
from and writing to byte streams, respectively. In this section, you are going to learn of data
transforming and manipulating using Filter Streams. 
Like I/O streams, Filter streams are also used to manipulate data reading from an underlying
stream. Apart from this, it allows the user to make a chain using multiple input stream so that,
the operations that are to be applied on this chain, may create a combine effects on several
filters. By using these streams, there is no need to convert the data from byte to char while
writing to a file. These are the more powerful streams than the other streams of Java.
The class hierarchy of the Filter streams derived from I/O streams can be shown as:

There are two streams, that are derived from the I/O stream class:

 FilterInputStream
 FilterOutputstream
FilterInputStream:
FilterInputStream is the base class for all the input stream filters and is obtained from the
InputStream class. It simply overrides all the methods of the InputStream class required to
filter data. These methods performs some sort of filtering operations on the data and cannot be
instantiated directly. It provides the additional and chaining functionality for the multiple input
streams to be filtered.
The constructor of the FilterInputStream is written as:
FilterInputStream fis = new
FilterInputStream(Inputstream in); 
FilterOutputstream:
FilterOutputStream is the super class of all the output stream filters and is obtained from the
OutputStream class. It simply overrides all the methods of the OutputStream class required
to filter the data that is written to the output stream.
FilterIntputStream and FilterOutputStream do not perform any filtering themselves; this is
done by their subclasses. To improve the performance of these I/O streams, their subclasses
BufferedInputStream and BufferedOutputStream are used.
BufferedInputStream:
This class is a subclass of the FilterInputstream class that lets you read large amount of data
from a stream and store it in an internal buffer. When data is requested, it is usually read from
the buffer. This has the effect for improving the performance of some input streams, especially
for those, that are bounded to slower sources like a file or network connection.
The constructor of the BufferedInputStream is written as:
BufferedInputStream (java.io.InputStream in);

BufferedOutputStream:
This is a subclass of the BufferedOutputStream and a buffered output stream that lets you
write characters to a stream. A BufferedOutputStream adds functionality to another output
stream. The data is first written into a buffer. When the BufferedOutputStream is created, an
internal buffer array is also created, in which the bytes are stored.
The constructor of the BufferedOutputStream is written as:
BufferedOutputStream (java.io.OutputStream out);

Write to a file

As we have read about  the BufferedOutputStream class that store the data in an internal
buffer and lets you write characters to a stream. Lets see an example that writes the text "Hello
Java" to the existed file.
The given example uses the BufferedOutputstream class that writes the bytes to the output
stream. The output stream is a file "Filterfile.txt" in which the data is written in form of a
byte. The getBytes( ) method of the String class returns the bytes from the string.
 
import java.io.*; 

class WriteFilter
{
    public static void main(String args[])
    {
    String str="Hello Java";
        try 
        {
      FileOutputStream fos = new FileOutputStream("Filterfile.txt");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
      
            // Now write to the buffered stream.
           bos.write(str.getBytes());
           bos.flush();
                System.out.print("the data has been written");                 

        } 
        catch (Exception e) 
        {
            System.err.println("Error writing to a file: " + e);
        }
    }
}
Output of the Program:

C:\nisha>javac
WriteFilter.java

C:\nisha>java
WriteFilter
the data has been
written
C:\nisha>
Download this Program

Read the file

As we have read about  the BufferedInputStream class that lets you read characters from a
stream and stores it in an internal buffer. Lets see an example that reads the contains of the
existed file.
The given example uses the BufferedInputstream class that reads the bytes from the input
stream. The input stream is a file "Filterfile.txt" from which the data is read in form of a byte
through the read( ) method. The read( ) method reads the byte from the file that is converted
into the character-form.
 
import java.io.*; 

class ReadFilter
{
    public static void main(String args[])
    {
        try 
        {
      FileInputStream fin = new FileInputStream("Filterfile.txt");
            BufferedInputStream bis = new BufferedInputStream(fin);
      
            // Now read the buffered stream.
            while (bis.available() > 0) 
            {
                System.out.print((char)bis.read());
            }
        
        } 
        catch (Exception e) 
        {
            System.err.println("Error reading file: " + e);
        }
    }
}
Output of the Program:

C:\nisha>javac
ReadFilter.java

C:\nisha>java
ReadFilter
This is a text file
C:\nisha>
Download this Program

Another Streams

Filter Files in Java

Introduction
The Filter File Java example code provides the following functionalities:
 Filtering the files depending on the file extension provided by the user
  
 User provides the file extension and then program lists all the matching files found

Program accepts directory name and file extension from user and displays the files present in
the directory.
Program begins with import statement java.io.*; package, which is required for any
input/output operations.
Classes Defined in the program:
OnlyExt
The constructor of the class takes file extension as parameter and then prefix it with "*." and
assign into the global variable ext. The OnlyExt class implements FilenameFilter interface, so
we have to implement the abstract method accept( ) defined in the FilenameFilter interface.
The accept( ) method tests if a specified file should be included in a file list.
FilterFiles: 
The FilterFiles contains the public static void main(String args[]), which is the
entry point of our program. The program first accepts directory name and file extension from
the user and creates the object of OnlyExt class passing file extension as constructor
parameter.
Here is the code of the program :
import java.io.*;

  class OnlyExt implements FilenameFilter{

  String ext;

 
 public OnlyExt(String ext){
 
    this.ext="." + ext;
  }
  

  public boolean accept(File dir,String name){
 
    return name.endsWith(ext);
  }
}
 
public class FilterFiles{
 
 public static void main(String args[]) throws IOException{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in))
;
    System.out.println("Please enter the directory name : ");

    String dir = in.readLine();
    System.out.println("Please enter file type : ");

      String extn = in.readLine();
   
     File f = new File(dir);

    FilenameFilter ff = new OnlyExt(extn);
    
    String s[] = f.list(ff);

    for (int i = 0; i < s.length; i++){
 
      System.out.println(s[i]);

    }
 
  }

Download this example.

You might also like