File Input and Output

 

The programs we've written so far, except "Array ," the data are require to re-enter each the we re-run the program. This is because the data is stored in RAM, and it will disappear once the program stops running. To retrieve the data, a program must have a way of saving the data, hence Java API provides several classes that we can use for writing data to a file and reading data from a file. To write data to a file, we can use the PrintWriter class, and optionally, the FileWriter class. To read data from a file, we can use the Scanner class and the File class.

In general, there are two types of files: text and binary. A text file contains data that has been encoded as text, using a scheme such as Unicode. Even the file contains numbers, those numbers are stored in the file as a series of characters, in other word they are stored as " Strings ." As a result, the file may be opened and viewed in a text editor such as Notepad. A binary file contains data that has not been converted to text. As a result, we can not view the contents of a binary file with a text editor. As of this chapter, we will only discuss how to open and view text files.

The Java API provides a number of class that we will use to work with files. Hence, in order to use these classes, we will need to import the java I/O.

import java.io.*;

The statement needs to place on the top of the program before we can open/create any text files.

 

Using the PrintWriter class to write data to a File

To write data to a file, we will need to create an instance of the PrintWriter class. The PrintWriter class allows us to open a file for writing. We can write data to the file using the same print and println methods that we've been using to display data on the screen. In order for us to open a text file for writing, the text file that we create must be in the same directory as the program. For example, all the programs I've written so far they are locate in "C:\java\", so the text file I create must be in "C:\java\". If the program and the text file are in a different directory, we wouldn't be able to open the text file.

Note: Whenever we open a file, we have to close the file.

Opening a file

PrintWriter pw = new PrintWriter("Name.txt");

The above statement creates an empty file called Name.txt and establish a connection between it, and the PrintWriter object is referenced by pw. The file will be created in the same directory or folder as the program. Thus, whenever we want to write data into the text file, we use the key word pw.  In addition to that, we have to throw IOException, it's an exception handling, we have to put it right after public static void main(String[] args), or else we would get an error saying unreported excpetion has been caught. Here is a piece of code that will create a new text file, then writes data into the file.

// Opens the text file Name.txt, if it doesn't exists it will create a new one

PrintWriter pw = new PrintWriter("Name.txt");

// Writes Joe into the file

pw.println("Joe");

// Closes the file

pw.close();

Now lets observe a basic example

/*
    The program demonstrate a simple File Input

*
*/

import java.util.*;
// Needed for Scanner class
import java.io.*;
// Needed for File input and output

public class FileIn
{
    public static void main(String[] args)throws IOException
    {
        Scanner key = new Scanner(System.in);

        // Opens the file or create a file if it doesn't exist

        PrintWriter pw = new PrintWriter("Name.txt");

        for(int i=0; i<3; i++)
        {
           
// Gets the name from the user

            System.out.println("Enter a name: ");
            String name = key.nextLine();

            // Writes the name into the file
            pw.println(name);
        }

     
  /*
            Closes the file
            A step that always need to remember to do

        *
        */

        pw.close();
    }
}

ClickHere to download FileIn.java

The above program does not append the names, which means whenever we run the program to re-enter names, it will replace the original names with the new one. In addition to that, it doesn't give the user much choices with the name of the file. Hence, we will see a program below that allows the user to create the name of the file and append names to a text file. Thus, it gives the user more options and choices. To append data to a file we would have to use the FileWriter class, hence we would have the following two statements:

FileWriter fwriter = new FileWriter("Name.txt", true);
PrintWriter pw = new PrintWriter(fwriter);

This creates a PrintWriter object that can be used to write data to the file Name.txt, we set it to be true so that any data that is written to the file will be appended.

Appending data to a File

/*
    The program demonstrate a simple File Input that appends data
    In addition, it allows the user to create the name of file

*
*/

import java.util.*; // Needed for Scanner class
import java.io.*; // Needed for File input and output

public class FileAppend
{
    public static void main(String[] args)throws IOException
    {
        Scanner key = new Scanner(System.in);

        // Asks the user for how many name will be enter

        System.out.println("How many names are you going to enter: ");
        int num = key.nextInt();

        // Ask the user for the name of the file

        System.out.println("Enter the name of the file: ");
        String filename = key.next();

        // Opens the file or create a file if it doesn't exist

        FileWriter fw = new FileWriter(filename, true);
        PrintWriter pw = new PrintWriter(fw);

        for(int i=0; i<num; i++)
        {
           
// Gets the name from the user

            System.out.println("Enter a name: ");
            String name = key.next();

           
// Writes the name into the file
            pw.println(name);
        }

      
 /*
            Closes the file
            A step that always need to remember to do

        *
        */

        pw.close();
    }
}

ClickHere to download FileAppend.java

Reading Data from a File

Reading data from a file is very similar from writing data to a file. We need to have the two import statements, java.util.*; and java.io.*; where util.* is for the Scanner class and .io*; is for the input and output file class. In addition to that we still need to have throws IOExcpetion after main for throwing input/output exceptions. Here is an example on how to open a file:

    File file = new File("MyName.txt");
    Scanner input = new Scanner(file);

Here we created an instance of the File class, then it's used to represent a file. Notice here we passed the string "MyName.txt" to the constructor. This creates a file object that represent the file MyName.txt. Hence, whenever we want to read a line from the file we use the key word input. Lets see an example on how to read a single line from a file.

/*
    This is a simple program that reads a line from a text

*
*/


import java.util.*;
import java.io.*;

public class ReadLine
{
    public static void main(String[] args)throws IOException
    {
        Scanner key = new Scanner(System.in);

      
 // Gets the name of the file

        System.out.println("Enter the name of the file:");
        String filename = key.nextLine();

     
  // Opens the file

        File file = new File(filename);
        Scanner input = new Scanner(file);

     
  // Reads the first line of the file

        String line = input.nextLine();

       
// Prints the data to the screen

        System.out.println("The first line in the file is: ");
        System.out.println(line);

       
// Close the file

        input.close();
    }
}

Here is an output of the program:

Enter the name of the file:
Name.txt
The first line in the file is:
jj

ClickHere to download ReadLine.java

Reading until end of File

That only reads the first line, but what if we want to continue reading until we reach the end of the file. The Scanner class has a method named hasNext that can be used to determine whether the file has more data that can be read. If the end of the file has been reached and there is no more data to read, the hasNext method will end. Now lets observe an improve of our previous example:

/*
    This is a simple program that reads until the end of file

*
*/


import java.util.*;
import java.io.*;

public class DetectEndOfFile
{
    public static void main(String[] args)throws IOException
    {
        Scanner key = new Scanner(System.in);

      
 // Gets the name of the file

        System.out.println("Enter the name of the file:");
        String filename = key.nextLine();

       
// Opens the file

        File file = new File(filename);
        Scanner input = new Scanner(file);

       
// Reads until end of file

        while (input.hasNext())
        {
           
// Read a single line from the file

            String line = input.nextLine();

          
 // Prints the data to the screen

            System.out.println(line);
        }

       
// Close the file

        input.close();
    }
}
 

Here is the output of the program:

Enter the name of the file:
Name.txt
jj
jo
hi

ClickHere to download DetectEndOfFile.java

Reading Primitive Values from a File

Recall, the Scanner class provides method for reading primitive values. These methods are named nextByte, nextDouble, nextInt, nextFloat, NextLong, nextShort. Reading the primitive values from a file is the same as reading String. Lets see a basic example:

/*
    The program reads the Number.txt
    It will sums up all the number inside it
    Then it outputs to the screen

*
*/


import java.util.*;
import java.io.*;

public class FileNum
{
    public static void main(String[] args)throws IOException
    {
        Scanner key = new Scanner(System.in);

        int sum = 0;

     
  // Gets the name of the file

        System.out.println("Enter file name: ");
        String filename = key.nextLine();

      
 // Opens the file

        File file = new File(filename);
        Scanner input = new Scanner(file);

    
   /*
            Reads until the end of file
            Sums up all the number
        *
        */


        while(input.hasNext())
        {
            int number = input.nextInt();

            sum += number;

        }

        input.close();

        System.out.println("The sum of the number is " + sum);
    }
}

Here is the output of the program:

Enter file name:
Number.txt
The sum of the number is 20

ClickHere to download FileNum.java

Checking for File's Existence

It's usually a good idea to make sure if a file exists before we try to open the file for input. Hence, the File class has the exists method which allows us to check if a file exists or not. Lets see an example on how to use the exists method.

/*
    This program check for file existence

*
*/

import java.util.*;
import java.io.*;

public class FileExist
{
    public static void main(String[] args)throws IOException
    {
        Scanner key = new Scanner(System.in);

        int sum = 0;

       
// Gets the name of the file

        System.out.println("Enter file name: ");
        String filename = key.nextLine();

        // Checks if the file exists or not

        File file = new File(filename);

        if(!file.exists())
        {
            System.out.println("The file " + file +" is not found.");
            System.exit(0);
        }

       
// If file exists open for reading

        Scanner input = new Scanner(file);

      
 /*
            Reads until the end of file
            Sums up all the number
        *
        */


        while(input.hasNext())
        {
            int number = input.nextInt();

            sum += number;

        }

        input.close();

        System.out.println("The sum of the number is " + sum);
    }
}

ClickHere to download FileExist.java

File Exception Handling

/*
    The program demonstrate a simple File Exception

*
*/

import java.util.*;
// Needed for Scanner class
import java.io.*;
// Needed for File input and output

public class FileException
{
    public static void main(String[] args)
    {
        Scanner key = new Scanner(System.in);

        try
        {

            // Opens the file or create a file if it doesn't exist


            PrintWriter pw = new PrintWriter("Name.txt");

            for(int i=0; i<3; i++)
            {

                // Gets the name from the user

                System.out.println("Enter a name: ");
                String name = key.nextLine();

                // Writes the name into the file

                pw.println(name);
            }

           
/*
                Closes the file
                A step that always need to remember to do

            *
            */


          pw.close();
        }
        catch(IOException ae)
         {
            System.out.println("Invalid");
            System.exit(0);
        }


    }
}
 

ClickHere to download FileException.java

Notice, here we didn't put throws IOException after the main, instead we try to catch the Exception inside the main method.

 


 

 

  <Java 24><Home>