File Processing in Java

TOPICS


Input/Output/Files
File Input Using Scanner
Line-Based File Processing
File Output Using PrintStream
Sample programs (Program#1, Program#2, Program#3, Program#4).

OUTLINE



1. Input/Output/Files

1. Import the necessary classes from the packages java.util and java.io into the program.
2. Create and associate the appropriate objects with the I/O sources.
3. Use the appropriate methods associated with the variables created in Step 2 to input/output the data.
4. Close the files.

 
File someFile = new File("inputFile.txt");

 
File someFile = new File("inputFile.txt");
if (someFile.exists())
     someFile.delete();

2. File Input Using Scanner

 
File someFile = new File("inputFile.txt");
Scanner inputFile = new Scanner(someFile);

The first statement declares a stream named someFile that is associated with a text file named inputFile.txt.  The second statement creates a Scannerobject for this file (inputFile). This can also be done in one statement:
 

Scanner inputFile = new Scanner(new File("input.txt"));

 
Scanner <name> = new Scanner(new File("<file name>"));

...
Scanner inputFile = null;
boolean fileOpened = true;
int sum = 0;

try {
    inputFile = new Scanner(new File("input.txt"));
}
catch (FileNotFoundException e) {
    System.out.println("--- File Not Found! ---");
    fileOpened = false;
}

if (fileOpened) {
    //while there is more input to be read:
    while (inputFile.hasNext()) {
        //some kind of processing:
        sum += inputFile.nextInt();
    //continue processing here
    }
}

NOTE:  Every input and every output file used by your program has 2 names. The external file name is the real name of the file, as it is saved on your disk (used by the operating system). This name is used just once (numbers.txt); after that, you always use the stream name as the name of the file (inputFile). The stream name serves as a temporary name for the file, and is the name that is primarily used within the program.
 

Scanner inputFile = new Scanner(new File("dataFiles/input.txt"));

If your program is in  C:/MyDocuments/Java/Lab8, Java will look for:  C:/MyDocuments/Java/Lab8/dataFiles/input.txt.

1. (catch) Declare that the program will handle ("catch") the exception
Sample program:

 
import java.io.*; // for File, FileNotFoundException
import java.util.*; // for Scanner

public class ReadFile_1 {
    public static void main(String[] args){
        boolean fileOpened = true;
        File someFile = new File("input.txt");
        Scanner inputFile = null;
        String text;

        try {
            inputFile = new Scanner(someFile);
        }
        catch (FileNotFoundException e) {
            System.out.println("--- File Not Found! ---");
            fileOpened = false;
        }
        if(fileOpened && inputFile.hasNext()) {

            while(inputFile.hasNext()) {
                text = inputFile.next();
                System.out.println(text);
            }
            inputFile.close();
        }
    }
}

OUTPUT:
abcdefghijklmnoprstuvxyz
1
2
3
for the input.txt file as input:
abcdefghijklmnoprstuvxyz
1 2 3

2. (throw) Explicitly state that we choose not to handle the exception, and we accept that our program will crash if an exception occurs ( "throwing" the exception). When choosing this option the program needs a throws clause (keywords on a method's header to state that it may throw an exception.). If an input file does not exist, the program throws a FileNotFoundException. If an output file cannot be created or accessed, the program throws a FileNotFoundException. When we do not need the method main to handle the FileNotFoundException exception, we simply include a command in the heading of main to throw the FileNotFoundException exception.

General syntax (throws clause):
  public static <type> <name>(<params>) throws <type> {...

Example (file I/O throw exception)
 

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

Sample program:
 

import java.io.*; // for File, FileNotFoundException
import java.util.*; // for Scanner

public class ReadFile_2{
    public static void main(String[] args)throws FileNotFoundException {
        Scanner inputFile = new Scanner(new File("input.txt"));
        while(inputFile.hasNext()) {
            String text = inputFile.next();
            System.out.println(text);
        }
        inputFile.close();
    }
}

OUTPUT:
abcdefghijklmnoprstuvxyz
1
2
3
for the input.txt file as input:
abcdefghijklmnoprstuvxyz
1 2 3

 

//VERSION #1
//Displays the first 3 numbers in a file, and displays their sum at the end.
import java.io.*; // for File, FileNotFoundException
import java.util.*; // for Scanner

public class SumOfThree {
    public static void main(String[] args)throws FileNotFoundException {
        Scanner inputFile = new Scanner(new File("numbers.txt"));
        int first, second, third, sum = 0;
        first = inputFile.nextInt();
        second = inputFile.nextInt();
        third = inputFile.nextInt();
        sum = first + second + third;
        System.out.println("The first 3 numbers in file are: " + first + ", " + second + ", " + third);
        System.out.println("Their sum = " + sum);
        inputFile.close();
    }
}
OUTPUT:
The first 3 numbers in file are: 1, 2, 3
Their sum = 6
for the numbers.txt file as input: 1 2 3 4 5 6 7 8 9 10

NOTE: This program is very impractical because it only processes exactly 3 values from the input file. A better program would read the entire file, regardless of how many values it contains, using an EOF-controlled loop.

//VERSION #2
//Displays all numbers in a file, and displays their sum at the end.
import java.io.*; // for File, FileNotFoundException
import java.util.*; // for Scanner

public class SumOfAll_1 {
    public static void main(String[] args)throws FileNotFoundException {
        Scanner inputFile = new Scanner(new File("numbers.txt"));
        int num, sum = 0;
        while(inputFile.hasNextInt()) {
            num = inputFile.nextInt();
            System.out.println("The number = " + num);
            sum = sum + num;
        }
        System.out.println("The sum of all numbers/file = " + sum);
        inputFile.close();
    }
}
OUTPUT:
The number = 1
The number = 2
The number = 3
The number = 4
The number = 5
The number = 6
The number = 7
The number = 8
The number = 9
The number = 10
The sum of all numbers/file = 55
for the numbers.txt file as input: 1 2 3 4 5 6 7 8 9 10

NOTE: Could modify the program to ignore (skip) non-numeric values:

//VERSION #3
//Displays all numbers in a file, and displays their sum at the end.
import java.io.*; // for File, FileNotFoundException
import java.util.*; // for Scanner

public class SumOfAll_2 {
    public static void main(String[] args)throws FileNotFoundException {
        Scanner inputFile = new Scanner(new File("numbers.txt"));
        int num, sum = 0;
        while(inputFile.hasNext()) {
            if(inputFile.hasNextInt()) {
                num = inputFile.nextInt();
                System.out.println("The number = " + num);
                sum = sum + num;
            }
            else {
                inputFile.next(); //consume unwanted input
            }
        }
        System.out.println("The sum of all numbers/file = " + sum);
        inputFile.close();
    }
}
OUTPUT:
The number = 1
The number = 2
The number = 3
The number = 4
The number = 5
The number = 6
The number = 7
The number = 8
The number = 9
The number = 10
The sum of all numbers/file = 55
for the numbers.txt file as input: 1 a 2 b 3 c 4 5 6 7 8 9 10

NOTE: Could  modify the program to ignore (skip) non-numeric values and count how many numerical values/file:

//VERSION #4
//Displays all numbers in a file, counts them, and displays their sum at the end.
import java.io.*; // for File, FileNotFoundException
import java.util.*; // for Scanner

public class SumOfAll_3 {
    public static void main(String[] args)throws FileNotFoundException {
        Scanner inputFile = new Scanner(new File("numbers.txt"));
        int num, sum = 0, count = 0;
        while(inputFile.hasNext()) {
            if(inputFile.hasNextInt()) {
                num = inputFile.nextInt();
                count++;
                System.out.println("Number # " + count + " is: " + num);
                sum = sum + num;
            }
            else {
                inputFile.next(); //consume unwanted input
            }
        }
        System.out.println("The sum of " + count + " numbers/file = " + sum);
        inputFile.close();
    }
}
OUTPUT:
Number # 1 is: 1
Number # 2 is: 2
Number # 3 is: 3
Number # 4 is: 4
Number # 5 is: 5
Number # 6 is: 6
Number # 7 is: 7
Number # 8 is: 8
Number # 9 is: 9
Number # 10 is: 10
The sum of 10 numbers/file = 55
for the numbers.txt file as input: 1 a 2 b 3 c 4 5 6 7 8 9 10

3. Line-Based File Processing: nextLine

Scanner inputFile = new Scanner(new File("<file name>"));
while (inputFile.hasNextLine()) {
    String line = inputFile.nextLine();
    //start processing this line from here...
}

VERSION #1 (try/catch)

VERSION #2 (throw)

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

public class NumberLines {
    public static void main(String[] args) {
        boolean fileOpened = true;
        Scanner inputFile = null;
        int count = 1;
        try {
            inputFile = new Scanner(new File("text.txt"));
        }
        catch (FileNotFoundException e) {
            System.out.println("--- File Not Found! ---");
            fileOpened = false;
        }
        if(fileOpened) {
            while (inputFile.hasNextLine()) {
                String line = inputFile.nextLine();
                System.out.println(count + " " + line);
                count++;
            }
            inputFile.close();
        }
    }
}

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

public class NumberLines2 {
  public static void main(String[] args)
                          throws FileNotFoundException {
        Scanner inputFile = new Scanner(new File("text.txt"));
        int count = 1;
        while (inputFile.hasNextLine()) {
            String line = inputFile.nextLine();
            System.out.println(count + " " + line);
            count++;
        }
        inputFile.close();
    }
}

//in red: the code common to both versions
 
 
 
 

 

 

OUTPUT (for both versions)

For the text.txt file

1 abcdefghijklmnoprstuvxyz
2 1 2 3 4 5
3 a b c
4  x c v b ghnfghnn
5 234 567 12345
6 qweq weqwrewrwqrewqwefdf

abcdefghijklmnoprstuvxyz
1 2 3 4 5
a b c
 x c v b ghnfghnn
234 567 12345
qweq weqwrewrwqrewqwefdf

Scanner inputFile = new Scanner(new File("<file name>"));
while (inputFile.hasNextLine()) {
    String line = inputFile.nextLine();
    Scanner lineScan = new Scanner(line);
    //start processing this line from here...
}

4. File Output using PrintStream

Version #1(try/catch)

Version #2(try/catch/finally)

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

public class FileOutput_1 {
    public static void main(String[] args) {
        PrintStream outStream = null;
        try {
           outStream = new PrintStream(new File("out.txt"));
        }
        catch(FileNotFoundException e) {
           System.out.println("Error opening the file out.txt.");
           System.exit(0);
        }
        outStream.println("Some processing.");
        outStream.println("This is first line.");
        outStream.println("This is second line.");
        outStream.close( );
    }
}

 

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

public class FileOutput_2 {
    public static void main(String[] args) {
        PrintStream outStream = null;
        // OPEN the file here as in previous code
        try {
            outStream = new PrintStream(new File("out.txt"));
            outStream.println("Some processing.");
            outStream.println("This is first line.");
            outStream.println("This is second line.");
        }
        catch (IOException e) {
            System.out.println(e.getMessage());
        }
        finally  { // always close the file
            outStream.close( );
        }
   }
}

OUTPUT (in file out.txt) for both versions:
Continue processing.
This is first line.
This is second line.

5. Discussion Programs



#1.  Read in from the file numbers.txt pairs of integers and display the larger of each pair  to the screen.
 

VERSION #1 (try/catch)

VERSION #2 (throw)

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

public class MaxOfTwo {
    public static void main(String[] args) {
        boolean fileOpened = true;
        Scanner inputFile = null;

        try {
            inputFile = new Scanner(new File("input.txt"));
        }
        catch (FileNotFoundException e) {
            System.out.println("--- File Not Found! ---");
            fileOpened = false;
        }
        if(fileOpened) {
           while (inputFile.hasNextInt()) {
                int first = inputFile.nextInt();
                int second = inputFile.nextInt();
                if(first > second)
                    System.out.println(first + " > " + second);
                else if(second > first)
                    System.out.println(second + " > " + first);
                else
                    System.out.println(" Same values ");
            }
            inputFile.close();
        }
    }
}

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

public class MaxOfTwo2 {
    public static void main(String[] args)
                            throws FileNotFoundException {
        Scanner inputFile = new Scanner(new File("input.txt"));
       while (inputFile.hasNextInt()) {
             int first = inputFile.nextInt();
             int second = inputFile.nextInt();
             if(first > second)
                 System.out.println(first + " > " + second);
             else if(second > first)
                 System.out.println(second + " > " + first);
             else
                 System.out.println(" Same values ");
        }
        inputFile.close();
    }
}

//in red: the code common to both versionss
 
//both versions: any possible problems?  
 
 
 

 

OUTPUT for both versions:
12 > 10
47 > 23
61 > 5

for input.txt file as input:
10 12 23 47 5 61



#2. Read in and sum 100 numbers from a file and display their average on the screen.
 
 

VERSION #1 (try/catch)

VERSION #2 (throw)

import java.io.*; // for File, FileNotFoundException
import java.util.*; // for Scanner

public class AvgOf_MAX {
    public static final int MAX = 100;
    public static void main(String[] args){
        boolean fileOpened = true;
        Scanner inputFile = null;
        int num, sum = 0, count = 0;
        double avg;

        try {
            inputFile = new Scanner(new File("input.txt"));
        }
        catch (FileNotFoundException e) {
            System.out.println("--- File Not Found! ---");
            fileOpened = false;
        }
        if(fileOpened) {
          while(inputFile.hasNext()) {
             if(inputFile.hasNextInt() && count < MAX)) {
                num = inputFile.nextInt();
                count++;
                System.out.println("Number # " + count + " is: " + num);
                sum = sum + num;
             }
             else {
                inputFile.next(); //consume unwanted input
             }
          }
          avg = (double)sum / count;
          System.out.printf("The average of %d numbers/file = %.2f\n", count, avg);
          inputFile.close();
       }
    }
}

import java.io.*; // for File, FileNotFoundException
import java.util.*; // for Scanner

public class AvgOf_MAX2 {
   public static final int MAX = 100;
   public static void main(String[] args)
                            throws FileNotFoundException {
      Scanner inputFile = new Scanner(new File("input.txt"));
      int num, sum = 0, count = 0;
      double avg;

      while(inputFile.hasNext()) {
         if(inputFile.hasNextInt() && count < MAX) {
            num = inputFile.nextInt();
            count++;
            System.out.println("Number # " + count + " is: " + num);
            sum = sum + num;
         }
         else {
            inputFile.next(); //consume unwanted input
         }
       }
       avg = (double)sum / count;
       System.out.printf("The average of %d numbers/file = %.2f\n", count, avg);
       inputFile.close();
   }
}

//in red: the code common to both versions
 
//both versions: any possible problems? 
 
 
 

 

OUTPUT for both versions:
Number # 1 is: 10
Number # 2 is: 12
Number # 3 is: 23
Number # 4 is: 47
Number # 5 is: 5
Number # 6 is: 61
The average of 6 numbers/file = 26.33

for input.txt file as input:
10 12 23 47 5 61



#3. Take input from a file containing daily temperatures and print the difference between each adjacent pair of temperatures.
 

VERSION #1 (try/catch)

VERSION #2 (throw)

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

public class Temperatures {
  public static void main(String[] args) {
    boolean fileOpened = true;
    Scanner inputFile = null;

    try {
       inputFile = new Scanner(new File("temps.txt"));
    }
    catch (FileNotFoundException e) {
       System.out.println("--- File Not Found! ---");
       fileOpened = false;
    }
    if(fileOpened) {
       int temp1 = inputFile.nextInt();
       while (inputFile.hasNextInt()) {
          int temp2 = inputFile.nextInt();
          System.out.println("Temperature changed by " + (temp2 - temp1) + " deg. F");
          temp1 = temp2;
       }
       inputFile.close();
     }
  }
}

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

public class Temperatures2 {
  public static void main(String[] args)
                     throws FileNotFoundException {
     Scanner inputFile = new Scanner(new File("temps.txt"));

     int temp1 = inputFile.nextInt();
     while (inputFile.hasNextInt()) {
        int temp2 = inputFile.nextInt();
        System.out.println("Temperature changed by " + (temp2 - temp1) + " deg. F");
        temp1 = temp2;
      }
      inputFile.close();
    }
}
 

//in red: the code common to both versions
//both versions: any possible problems?

 

OUTPUT for both versions:
Temperature changed by 12 deg. F
Temperature changed by -26 deg. F
Temperature changed by 10 deg. F
Temperature changed by -2 deg. F
Temperature changed by 16 deg. F
Temperature changed by -4 deg. F
for the temps.txt file as input:
101 113 87 97 95 111 107



#4. Same program + allow the user to input the file name.
 

VERSION #1 (try/catch)

VERSION #2 (throw)

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

public class Temperatures3 {
    public static void main(String[] args) {
      boolean fileOpened = true;
      Scanner inputFile = null;
      String fileName;
      Scanner input = new Scanner(System.in);
      System.out.print("Enter file name: ");
      fileName = input.nextLine();
      System.out.println();
      try {
         inputFile = new Scanner(new File(fileName));
      }
      catch (FileNotFoundException e) {
         System.out.println("--- File Not Found! ---");
         fileOpened = false;
      }
      if(fileOpened) {
         int temp1 = inputFile.nextInt();
         while (inputFile.hasNextInt()) {
            int temp2 = inputFile.nextInt();
            System.out.println("Temperature changed by " + (temp2 - temp1) + " deg. F");
            temp1 = temp2;
         }
         inputFile.close();
      }
   }
}

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

public class Temperatures4 {
  public static void main(String[] args)
                     throws FileNotFoundException{
     String fileName;
     Scanner input = new Scanner(System.in);
     System.out.print("Enter file name: ");

     fileName = input.nextLine();
     System.out.println();
     Scanner inputFile = new Scanner(new File(fileName));
     int temp1 = inputFile.nextInt();
     while (inputFile.hasNextInt()) {
        int temp2 = inputFile.nextInt();
        System.out.println("Temperature changed by " + (temp2 - temp1) + " deg. F");
        temp1 = temp2;
     }
     inputFile.close();
  }
}
//in blue: the code to get the file name as input from user
//in red: the code common to both versions
//both versions: any possible problems?
 
 

 

OUTPUT:
Enter file name: temps.txt

Temperature changed by 12 deg. F
Temperature changed by -26 deg. F
Temperature changed by 10 deg. F
Temperature changed by -2 deg. F
Temperature changed by 16 deg. F
Temperature changed by -4 deg. F

for the temps.txt file as input:
101 113 87 97 95 111 107


Additional Resources:
1. (Sun) API specification for version 6 of the Java™ Platform, Standard Edition:  http://java.sun.com/javase/6/docs/api/
2. (Sun) The Java Tutorials, Basic I/O, File Objects: http://java.sun.com/docs/books/tutorial/essential/io/file.html
3. (Sun) The Java Tutorials, Exceptions: http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html


References:
[1] Building Java Programs: A Back to Basics Approach, by Stuart Reges, and Marty Stepp, Addison Wesley, 2008.
[2] Java Programming: From Problem Analysis to Program Design, by D.S. Malik, Thomson Course Technology, 2008