Reading from a file and writing to a file using Java program

Java provides a number of classes and methods that allow you to read and write files. In Java, all files are byte-oriented, and Java provides methods to read and write bytes from and to a file. However, Java allows you to wrap a byte-oriented file stream within a character-based object. This tutorial examines the basics of file I/O.

Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files. To open a file, you simply create an object of one of these classes, specifying the name of the file as an argument to the constructor. While both classes support additional, overridden constructors, the following are the forms that we will be using:

FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException


Here, fileName specifies the name of the file that you want to open. When you create an input stream, if the file does not exist, then FileNotFoundException is thrown. For output streams, if the file cannot be created, then FileNotFoundException is thrown. When an output file is opened, any preexisting file by the same name is destroyed.


Several of the methods in this section take an optional Open Options parameter. This parameter is optional and the API tells you what the default behavior is for the method when none is specified.

The following Standard Open Options enums are supported:  

WRITE
   Opens the file for write access.

APPEND
 Appends the new data to the end of the file. This option is used with the WRITE or CREATE options.

TRUNCATE_EXISTING 
Truncates the file to zero bytes. This option is used with the WRITE option.

CREATE_NEW 
 Creates a new file and throws an exception if the file already exists.

 CREATE 
Opens the file if it exists or creates a new file if it does not.

 DELETE_ON_CLOSE
Deletes the file when the stream is closed. This option is useful for temporary files.

 SPARSE  Hints that a newly created file will be sparse. This advanced option is honored on some file systems, such as NTFS where large files with data "gaps" can be stored in a more efficient manner where those empty gaps do not consume disk space.

SYNC
 Keeps the file (both content and metadata) synchronized with the underlying storage device.

DSYNC
 Keeps the file content synchronized with the underlying storage device.



When you are done with a file, you should close it by calling close( ). It is defined by both FileInputStream and FileOutputStream, as shown here:

void close( ) throws IOException

To read from a file, you can use a version of read( ) that is defined within FileInputStream. The one that
 we will use is shown here:

int read( ) throws IOException

Each time that it is called, it reads a single byte from the file and returns the byte as an integer value. read( ) returns –1 when the end of the file is encountered. It can throw an IOException.
The following program uses read( ) to input and display the contents of a text file, the name of which is specified as a command-line argument. Note the try/catch blocks that handle the two errors that might occur when this program is used—the specified file not being found or the user forgetting to include the name of the file. You can use this same approach whenever you use command-line arguments.



import java.io.*;
class Fileinfo
 {
  public static void main(String args[]) throws IOException
   {
    int i;
    FileInputStream fin;
    try
     {
      fin = new FileInputStream(args[0]);
     }
    catch(FileNotFoundException e)
     {
      System.out.println("File Not Found");
      return;
     }
    catch(ArrayIndexOutOfBoundsException e)
     {
      System.out.println("Usage: ShowFile File");
      return;
     }

    do
     {
      i = fin.read();
      if(i != -1) System.out.print((char) i);
     }
    while(i != -1);
    fin.close();
  }
 }
Output 

G:\>javac Fileinfo.java
G:\>java Fileinfo
Usage: ShowFile File

Reading from a file and writing to a file using Java program

0 comments:

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org