Search Java Programs

Saturday, February 6, 2010

What is Java I/O?

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.

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 = 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.
 Method  Return Type  Description
 read( )  int  Reads a single character 
 read(char[] cbuf, int off, int len)  int  Read characters into a portion of an array.
 readLine( )  String  Read a line of text. A line is 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

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.GetField This class access to president 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.
     ObjectStreamConstants This interface used for Constants writing into Serialization Objects Stream.
 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.
UnsupportedEncodingException The Character Encoding is not 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.

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.

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

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

Introduction to Filter I/O Streams

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

Working with PrintStream

The PrintStream class is obtained from the FilterOutputstream class that implements a number of methods for displaying textual representations of Java primitive data types. It adds the functionality to another output streams that has the ability to print various data values conveniently. Unlike other output streams, a PrintStream never throws an IOException and the data is flushed to a file automatically i.e. the flush method is automatically invoked after a byte array is written,
The constructor of the PrintStream class is written as:
PrintStream (java.io.OutputStream out);   //create a new print stream
The print( ) and Println( ) methods of this class give the same functionality as the method of standard output stream and follow the representations with newline.
The given example demonstrate the writing operation to a file using PrintStream class.

import java.io.*;

class PrintStreamDemo {  
        public static void main(String args[]){   
               FileOutputStream out; 
                PrintStream ps; // declare a print stream object
                try {
                 // Create a new file output stream
                out = new FileOutputStream("myfile.txt");

                        // Connect print stream to the output stream
                        ps = new PrintStream(out);
    
                        ps.println ("This data is written to a file:");
            System.err.println ("Write successfully");
                        ps.close();
                }
                catch (Exception e){
                        System.err.println ("Error in writing to file");
                }
        }
}

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

C:\nisha>java PrintStreamDemo
Write successfully

C:\nisha>
This program firstly create an object "ps" of the PrintStream class the specified data is written through that object using the println( ) method.
Download this Program

Overview of I/O Data Streams

As mentioned earlier, Filter streams are special streams which filter input and output bytes and 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 I/O streams derived from I/O streams can be shown as:

In this section we will learn about the Data I/O streams derived from the Filter I/O streams.
DataStreams:
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. These streams filter an existing byte stream so that each primitive data types can be read from or written to the stream directly.
These Data Streams are as follows:
  • DataInputStream
  • DataOutputStream
DataInputStream:
This is a class derived from FilterInputStream class that allows you to read binary represented data of Java primitive data types from an underlying input stream in a machine-independent way. It reads only Java primitive data types and doesn't read the object values. A data input stream is created with the constructor of DataInputStream class. The specified argument that is to be filtered within the constructor should be an existing input stream  (such as a buffered input stream or a file input stream).
The constructor of DataInputStream is written as:
DataInputStream (java.io.InputStream in);
The read( ) method is used to read the data according to its types. For example, the readInt( ) method reads the int type of value while the readFloat() method reads the fraction value. The readLine( ) Methods reads the string per line from a file.
DataOutputStream:
This is a class derived from FilterOutputStream class that allows you to write binary represented data of Java primitive data types reading from an underlying output stream in a machine-independent way. It writes only Java primitive data types and doesn't write the object values. A data output stream is created with the constructor of DataOutputStream class. The specified argument that is to be filtered within the constructor should be an existing output stream  (such as a buffered output stream or a file output stream).
The constructor of DataOutputStream is written as:
DataOutputStream (java.io.OutputStream out);
The write( ) method is used to write the data according to its types. For example, the writeInt( ) method writes the int type of value while the writeFloat() method writes the fraction value. The writeUTF( ) method writes the string per line to a file.
Lets see an example that shows the implementation of reading and writing operations through the Data I/O streams.

import java.io.*; 

class ReadWriteData
{
    public static void main(String args[])
    {
    int ch=0;
    int[] numbers = { 12, 8, 13, 29, 50 };
        try 
        {
      
      System.out.println("1. write Data");
      System.out.println("2. Read Data");      
      System.out.println("Enter your choice ");
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      ch=Integer.parseInt(br.readLine());
      switch(ch){
        case 1:          
        FileOutputStream fos = new FileOutputStream("datafile.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        DataOutputStream out =new DataOutputStream (bos);
        for (int i = 0; i < numbers.length; i ++) {
                 out.writeInt(numbers[i]);
        }
         System.out.print("write successfully");    
         out.close();
        case 2:
          FileInputStream fis = new FileInputStream("datafile.txt");
              BufferedInputStream bis=new BufferedInputStream(fis);
              DataInputStream in =new DataInputStream (bis);
          while (true){
            System.out.print(in.readInt());
            }
                         
            default:
              System.out.println("Invalid choice");      
            }
            } 
        catch (Exception e) {
            System.err.println("Error in read/write data to a file: " + e);
        }
    
      }
}
Output of the Program:
C:\nisha>javac ReadWriteData.java

C:\nisha>java ReadWriteData
1. write Data
2. Read Data
Enter your choice
1
write successfully128132950
C:\nisha>
This program uses both DataInputStream and DataOutputStream to read and write data to the specified file respectively. If the user enters the choice as 1 then the specified data is written to a file through the object of DataOutputStream class using the writeInt( ) method. On the other hand, if the user enters the choice as 2 then the written data is read from the file through the object of DataInputStream class using the ReadInt( )
Here, another output is shown when the user enters the choice as 2.
C:\nisha>javac ReadWriteData.java  C:\nisha>java ReadWriteData
1. write Data
2. Read Data
Enter your choice
2
128132950

C:\nisha>
Download this Program

Using a Random Access File

Introduction
In this section, you will learn about the RandomAccess 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. As the name suggests, random that means it is not sequential and the data can be read from and written to any specified position in the file.

 Mostly, Users use the input stream or output stream in a sequential but Unlike the input and output streams java.io. RandomAccessFile is used for both reading and writing files A random access file treats with a large array of bytes stored in the file system and uses the file pointer  to deal with the indexe of that array. This file pointer points the positions in the file where the reading or writing operation has to be done.

Random AccessFile implements the same interfaces as the DataInputStream and the DataOutputStream. Thus it defines the same methods for reading and writing data to a file.
This program shows the implementation of the RandomAccessFile class. Program takes an input from user to the name of a file and  checks if it exists then it writes the specified string using the method writeChars( ); Otherwise it displays the appropriate message as  "File does not exist".  An IOException may be thrown if the stream has been closed.

 There are following methods has been used in this program:
RandomAccessFile rand = new RandomAccessFile(file,"rw");
The above code creates an instance of the RandomAccessFile class mentioning the mode in which file has to be opened. The constructor  RandomAccessFile( )  takes two arguments: First is the file name and another is the operation mode (read-write mode). We are opening the file into read and write mode ("rw").
There are following methods that are used in the given program shown as.
rand.seek(file.length());

This is the seek( ) method of the RandomAccessFile class has been used to jump the file pointer at the specified. Here, file.length( ) returns the end of the file.
rand.close();

This is the close( ) method of the RandomAccessFile class has been used to close the created the instance of the RandomAccessFile class.
writeBytes( ); 

This the writeBytes( ) method which simply writes the content into the file. This method always append the file content with your specified text.
Here is the code of the program :

import java.io.*;
 


public class RandAccessFile{

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


      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter File name : ");
    String str = in.readLine();
 
   File file = new File(str);
    if(!file.exists())
{
 
     System.out.println("File does not exist.");
  
    System.exit(0);
 
   }
   
 try{
      //Open the file for both reading and writing
      RandomAccessFile rand = new RandomAccessFile(file,"rw"); 
      
     rand.seek(file.length());  //Seek to end of file
      rand.writeBytes("Roseindia.net,");  //Write end of file 
 
      rand.close();
    
  System.out.println("Write Successfully");
  
  }
   
 catch(IOException e)
{
 
   System.out.println(e.getMessage());

      }
 
 }

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

C:\nisha>java RandAccessFile
Enter File name : Filterfile.txt
Write Successfully
Download this example.
The another program reads the characters from a file using the readByte( ) method.

import java.io.*;

public class ReadAccessFile{
  public static void main(String[] args) throws IOException{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter File name : ");
    String str = in.readLine();
    File file = new File(str);
    if(!file.exists())
    {
      System.out.println("File does not exist.");
      System.exit(0);
    }
    try{
      //Open the file for both reading and writing
      RandomAccessFile rand = new RandomAccessFile(file,"r"); 
      int i=(int)rand.length();
      System.out.println("Length: " + i);
         rand.seek(0);  //Seek to start point of file
      for(int ct = 0; ct < i; ct++){
        byte b = rand.readByte(); //read byte from the file
        System.out.print((char)b); //convert byte into char
      }
      rand.close();
    }
      catch(IOException e)
    {
    System.out.println(e.getMessage());
    }
  }
}
Output of the Program:
C:\nisha>java ReadAccessFile
Enter File name : Filterfile.txt
Length: 30
??t h i s i s a f i l e
C:\nisha>
Download this Program:

Making Tokens of a Java Source Code

This section of I/O tutorial will be helpful to understand Java programming in the most simplest and effecient way. 
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 it and parses it into "tokens", allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. This class is extended from the java.io and java.util package.
The use of  token is just as we take tokens for getting a milk or to enter in metro, so that the one token can be read at a time. 

Lets understand the example shown below:

In the given program, firstly we  make a class TokenizingJavaSourceCode.  Now make a object of BufferedReader class and pass the InputStream class object into it which will read the name of the java file at run time. Now we need to read the file so that we can use FileReader class ,After reading a file we need to generate a tokens out of that file so that we can use  the class StreamTokenizer and pass the reference of a Reader class in its constructor. In this program we are using one method of StreamTokenizer class. 

To solve this problem we have make use of the following classes and methods.
InputStream: It is a abstract class and the parent class of all the Stream classes.
BufferedReader: This class reads the text from the input stream. This class extends Reader class. 
File: It is a class implementing Serializable and Comparable interface.
FileReader:  This class  reads the file in the character format. It extends InputStreamReader.
StreamTokenizer: This class takes a input stream and break it into tokens so that one token can be read at a time. It takes FileReader instance as a input in its constructor. 
readLine(): It is a method of BufferedReader class which reads a line.
exists(): It will check whether the file exists or not.
nextToken(): It gives the next token.
We have also used one final static variable TT_EOF which tells the reader that the end of the file has been read.
The code of this program is given below:

import java.io.*; 

import java.util.*;

 

public class TokenizingJavaSourceCode{
  //public static final int TT_EOL;   
    public static void main(String[] args) throws IOException{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter a java file name: ");
    String filename = in.readLine();
 
 
  if(!filename.endsWith(".java")){
 
      System.out.println("This is not a java file.");

        System.exit(0);
  
  }
 
   
 File javaFile = new File(filename);
  
  if(javaFile.exists()){
 
      FileReader file = new FileReader(filename);
      StreamTokenizer streamTokenizer = new StreamTokenizer(file);
      // It will go through the file and gives the number of tokens in the file
      int i=0;
    
  int numberOfTokensGenerated = 0;
  
    while(i != StreamTokenizer.TT_EOF){
   
     i = streamTokenizer.nextToken();
   
     numberOfTokensGenerated++;
  
    }
     
 System.out.println("Number of tokens = " + numberOfTokensGenerated);
 
    }
   
 else{
   
   System.out.println("File does not exist!");
 
      System.exit(0);
   
 }
 
 }
 
}

Output of the program:
C:\Java Tutorial>java TokenizingJavaSourceCode
Please enter a java file name: TokenizingJavaSourceCode.java
Number of tokens = 158

C:\Java Tutorial>_
Download this program

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 directory.");
      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

Delete 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.in));
    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.

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 directory.");
      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

Getting the modification date and time of file or folder in Java

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 : 



<pre><span style=' color: Blue;'>import</span> java.io.*;
 
<span style=' color: Blue;'>import</span> java.util.*;
 
<span style=' color: Blue;'>public</span> <span style=' color: Blue;'>class</span> GetDirectoryAndFileModifiedTime{
 
  <span style=' color: Blue;'>public</span> <span style=' color: Blue;'>static</span> <span style=' color: Blue;'>void</span> main(String[] args) <span style=' color: Blue;'>throws</span> IOException{
    BufferedReader in = <span style=' color: Blue;'>new</span> BufferedReader(<span style=' color: Blue;'>new</span> 
                          InputStreamReader(System.in));
    System.out.println("Enter file or directory name in proper 
                        format to get the modification date and time : ");
    File filename = <span style=' color: Blue;'>new</span> File(in.readLine());
 
    <span style=' color: Blue;'>if</span> (filename.isDirectory()){
 
      <span style=' color: Blue;'>if</span> (filename.exists()){
 
       <span style=' color: Blue;'>long</span> t = filename.lastModified();
 
       System.out.println(<span style=' color: Maroon;'>"Directory name : "</span> + filename.getName());
        System.out.println("Directory 
                modification date and time : " + <span style=' color: Blue;'>new</span> Date(t)); 
     }
   
   <span style=' color: Blue;'>else</span>{
    
    System.out.println(<span style=' color: Maroon;'>"Directory not found!"</span>);
 
        System.exit(<span style=' color: Maroon;'>0</span>);
    
  }
   
 }
  
  <span style=' color: Blue;'>else</span>{
 
      <span style=' color: Blue;'>if</span> (filename.exists()){
 
       <span style=' color: Blue;'>long</span> t = filename.lastModified();
  
      System.out.println(<span style=' color: Maroon;'>"File name : "</span> + filename.getName());
        System.out.println("File 
                    modification date and time : " + <span style=' color: Blue;'>new</span> Date(t));
 
     }
  <span style=' color: Blue;'>else</span>{
    
    System.out.println(<span style=' color: Maroon;'>"File not found!"</span>);
 
       System.exit(<span style=' color: Maroon;'>0</span>);
   
   }
   
 }
  
}
 
}</pre>

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.

Website Design by Mayuri Multimedia