Home

File Processing

 

Files

 

Introduction

File processing is performed in Java using various classes. The primary class used to handle files is called File. The File class is part of the java.io package. To use it, you can start by importing it in your file. Here is an example:

import java.io.File;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	
    }
}

The File class is based on (implements) the FileOutputStream class. The FileOutputStream class is based on the OutputStream class. That is how it gets most of its functionality.

To use a file, declare a File variable using one of its constructors. One of the constructors takes one argument as a string, the name of the file or its complete path. Of course, if the file has an extension, you must include it. Here is an example:

import java.io.File;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	File fleExample = new File("Example.xpl");
    }
}

The only real thing the File class does is to indicate that you are planning to use a file. It does not indicate what you will do with the file. You must specify whether you will create a new file or open an existing one.

Practical LearningPractical Learning: Introducing File Processing

  1. Start NetBeans
  2. To create a Java Application, on the main menu, click File -> New Project...
  3. Select Java Application and click Next
  4. Set the Name to StudentUniversity1
  5. Set the Main Class name to Central
  6. Click Finish
  7. In the Projects window, right-click StudentUniversity1 -> New -> Java Package...
  8. Set the name to Students
  9. Click Finish
  10. To create a new class, in the Projects window, under StudentUniversity1, right-click Students -> New -> Java Class...
  11. Set the Name to Student
  12. Click Finish
  13. Change the file as follows:
     
    package Students;
    
    public class Student {
        public int StudentIdentificationNumber;
        public String FirstName;
        public String LastName;
        public int CreditsSoFar;
        public double GPA;
    }

Creating a File

If you want to create a new file, you must use a class that is equipped to write values to a file. To do this, you can use the PrintWriter class. The PrintWriter class is defined in the java.io package. Therefore, if you want to use it, you can import it in your document. This would be done as follows:

import java.io.PrintWriter;

public class Exercise {
    public static void main(String[] args)  throws Exception {

    }
}

The PrintWriter class is based on (implements) the Writer class. The class is equipped with the necessary means of writing values to a file.

Before using the class, declare a variable for it. This class is equipped with many constructors. One of the constructors takes as argument an OutputStream object. We saw that the File class is based on OutputStream. This means that you can pass a File object to a PrintWriter constructor. This would be done as follows:

import java.io.File;
import java.io.PrintWriter;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to use a file
	File fleExample = new File("Example.xpl");
        // Create that file and prepare to write some values to it
        PrintWriter pwInput = new PrintWriter(fleExample);
    }
}

Writing to a File

After creating a PrintWriter object, you can write values to the file. To support this, the PrintWriter class is equipped with the print() and println() methods that is overloaded with various versions for each type of values (boolean, char, char[], int, float, double, String, or Object). Therefore, to write a value to a file, call the appropriate version of the PrintWriter.print() method and pass the desired value. Here are examples:

import java.io.File;
import java.io.PrintWriter;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to use a file
	File fleExample = new File("Example.xpl");
        // Create that file and prepare to write some values to it
        PrintWriter pwInput = new PrintWriter(fleExample);

	// Write a string to the file
	pwInput.println("Francine");
	// Write a string to the file
     	pwInput.println("Mukoko");
	// Write a double-precision number to the file
	pwInput.println(22.85);
	// Write a Boolean value to the file
	pwInput.print(true);
    }
}

After using a PrintWriter object, you should free the resources it was using. To assist you with this, the PrintWriter class is equipped with the Close() method. Here is an example of calling:

import java.io.File;
import java.io.PrintWriter;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to use a file
	File fleExample = new File("Example.xpl");
        // Create that file and prepare to write some values to it
        PrintWriter pwInput = new PrintWriter(fleExample);

	// Write a string to the file
	pwInput.println("Francine");
	// Write a string to the file
     	pwInput.println("Mukoko");
	// Write a double-precision number to the file
	pwInput.println(22.85);
	// Write a Boolean value to the file
	pwInput.print(true);
	
        // After using the PrintWriter object, de-allocated its memory
        pwInput.close();
        // For convenience, let the user know that the file has been created
        System.out.println("The file has been created.");   
    }
}

Practical LearningPractical Learning: Creating a File

  1. Click the Central.java tab
  2. Change the file as follows:
     
    package studentuniversity1;
    import java.io.*;
    import Students.Student;
    import java.util.Scanner;
    
    public class Central {
        public static Student register() {
            Student kid = new Student();
            Scanner scnr = new Scanner(System.in);
            
            System.out.println("Enter information about the student");
            System.out.print("Student ID: ");
            kid.StudentIdentificationNumber = scnr.nextInt();
            System.out.print("First Name: ");
            kid.FirstName = scnr.next();
            System.out.print("Last Name: ");
            kid.LastName = scnr.next();
            System.out.print("Number of credits so far: ");
            kid.CreditsSoFar = scnr.nextInt();
            System.out.print("Grade point average: ");
            kid.GPA = scnr.nextDouble();
            
            return kid;
        }
    
        public static void save(Student pupil) throws Exception {
            String strFilename = "";
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Enter the file name: ");
            strFilename = scnr.next();
            
            // Make sure the user entered a valid file name
            if( !strFilename.equals("")) {
                // Indicate that you are planning to use a file
                File fleExample = new File(strFilename);
                // Create that file and prepare to write some values to it
                PrintWriter wrtStudent = new PrintWriter(fleExample);
    
                wrtStudent.println(pupil.StudentIdentificationNumber);
                wrtStudent.println(pupil.FirstName);
                wrtStudent.println(pupil.LastName);
                wrtStudent.println(pupil.CreditsSoFar);
                wrtStudent.println(pupil.GPA);
                
                // After using the PrintWriter object, de-allocated its memory
                wrtStudent.close();
                // For convenience, let the user know that the file has been created
                System.out.println("The file has been created.");
            }
        }
        
        public static void show(Student std) throws Exception {
            System.out.println("Student Record");
            System.out.println("Student ID: " + std.StudentIdentificationNumber);
            System.out.println("First Name: " + std.FirstName);
            System.out.println("Last Name: " + std.LastName);
            System.out.println("Number of credits so far: " + std.CreditsSoFar);
            System.out.println("Grade point average: " + std.GPA);
        }
        
        public static void main(String[] args) throws Exception {
            String answer = "n";
            Student std = register();
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Do you want to save this information (y/n)? ");
            answer = scnr.next();
            
            if( (answer.equals("y")) || (answer.equals("Y")) ) {
    	    show(std);
                save(std);
            }
        }
    
    }
  3. Press F6 to execute the application
  4. Enter the following information:
     
    Student ID: 927426
    First Name: Christopher
    Last Name Lame
    Credits so far: 38
    GPA 2.26
  5. When asked whether you want to save, click Yes
  6. Type Student1.txt as the file name and press Enter
  7. Execute the application again
  8. Enter the following information:
     
    Student ID: 286350
    First Name: June
    Last Name Glasnow
    Credits so far: 69
    GPA 3.15
  9. When asked whether you want to save, click Yes
  10. Type Student2.txt as the file name and press Enter
 
 
 
 

Opening a File

Besides creating a file, the second most common operation performed on a file consists of opening one. You can open a file using the File class. As done previously, first declare a File variable and pass the name of the file to its constructor. Here is an example:

import java.io.File;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Incidate that you are planning to opena file
	File fleExample = new File("Example.xpl");
    }
}

Reading From a File

To support the ability to read a value from a file, you can use the Scanner class. To support this operation, the Scanner class is equipped with a constructor that takes a File object as argument. Therefore, you can pass it a File variable you will have previously declared. Here is an example of declaring and initializing a variable for it:

import java.io.File;
import java.util.Scanner;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to opena file
	File fleExample = new File("Example.xpl");
        // Prepare a Scanner that will "scan" the document
        Scanner opnScanner = new Scanner(fleExample);
    }
}

The values of a file are stored in or more lines. To continuously read the lines from the file, one at a time, you can use a while loop. In the while loop, continuously use the Scanner object that can read a line of value(s). In the while statement, to check whether the Scanner object has not gotten to the last line, you can check the status of its hasNext() method. As long as this method returns true, the Scanner reader has not gotten to the end of the file. Once the Scanner object has arrived to the end, this method would return false. Here is an example of implementing this scenario:

import java.io.File;
import java.util.Scanner;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to opena file
	File fleExample = new File("Example.xpl");
        // Prepare a Scanner that will "scan" the document
        Scanner opnScanner = new Scanner(fleExample);

	// Read each line in the file
        while(opnScanner.hasNext()) {
            // Read each line and display its value
	    System.out.println("First Name:    " + opnScanner.nextLine());
	    System.out.println("Last Name:     " + opnScanner.nextLine());
	    System.out.println("Hourly Salary: " + opnScanner.nextLine());
	    System.out.println("Is Full Time?: " + opnScanner.nextLine());
	}
    }
}

After using the Scanner object, to free the resources it was using, call its close() method. Here is an example:

import java.io.File;
import java.util.Scanner;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to opena file
	File fleExample = new File("Example.xpl");
        // Prepare a Scanner that will "scan" the document
        Scanner opnScanner = new Scanner(fleExample);

	// Read each line in the file
        while( opnScanner.hasNext() ) {
            // Read each line and display its value
	    System.out.println("First Name:    " + opnScanner.nextLine());
	    System.out.println("Last Name:     " + opnScanner.nextLine());
	    System.out.println("Hourly Salary: " + opnScanner.nextLine());
	    System.out.println("Is Full Time?: " + opnScanner.nextLine());
	}
            
    	// De-allocate the memory that was used by the scanner
        opnScanner.close();
    }
}

Practical LearningPractical Learning: Opening a File

  1. Change the Central.java file as follows:
     
    package studentuniversity1;
    import java.io.*;
    import Students.Student;
    import java.util.Scanner;
    
    public class Main {
        public static Student register() {
            Student kid = new Student();
            Scanner scnr = new Scanner(System.in);
            
            System.out.println("Enter information about the student");
            System.out.print("Student ID: ");
            kid.StudentIdentificationNumber = scnr.nextInt();
            System.out.print("First Name: ");
            kid.FirstName = scnr.next();
            System.out.print("Last Name: ");
            kid.LastName = scnr.next();
            System.out.print("Number of credits so far: ");
            kid.CreditsSoFar = scnr.nextInt();
            System.out.print("Grade point average: ");
            kid.GPA = scnr.nextDouble();
            
            return kid;
        }
    
        public static void save(Student pupil) throws Exception {
            String strFilename = "";
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Enter the file name: ");
            strFilename = scnr.next();
            
            // Make sure the user entered a valid file name
            if( !strFilename.equals("")) {
                // Incidate that you are planning to use a file
                File fleStudent = new File(strFilename);
                // Create that file and prepare to write some values to it
                PrintWriter wrtStudent = new PrintWriter(fleStudent);
    
                wrtStudent.println(pupil.StudentIdentificationNumber);
                wrtStudent.println(pupil.FirstName);
                wrtStudent.println(pupil.LastName);
                wrtStudent.println(pupil.CreditsSoFar);
                wrtStudent.println(pupil.GPA);
                
                // After using the PrintWriter object, de-allocated its memory
                wrtStudent.close();
                // For convenience, let the user know that the file has been created
                System.out.println("The file has been created.");
            }
        }
        
        public static Student open()  throws Exception {
            String strFilename = "";
            String strStudentIdentificationNumber;
            String strCreditsSoFar;
            String strGPA;
            
            Student majoring = new Student();
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Enter the file name: ");
            strFilename = scnr.next();
            
            if( !strFilename.equals("") ) {
                // Indicate that you are planning to opena file
                File fleStudent = new File(strFilename);
                // Prepare a Scanner that will "scan" the document
                Scanner opnStudentInfo = new Scanner(fleStudent);
    
                // Read each line in the file
                while( opnStudentInfo.hasNext() ) {
                    // Read each line and display its value
                    strStudentIdentificationNumber = opnStudentInfo.nextLine();
                    majoring.StudentIdentificationNumber =
                            Integer.parseInt(strStudentIdentificationNumber);
                    majoring.FirstName = opnStudentInfo.nextLine();
                    majoring.LastName = opnStudentInfo.nextLine();
                    strCreditsSoFar = opnStudentInfo.nextLine();
                    majoring.CreditsSoFar = Integer.parseInt(strCreditsSoFar);
                    strGPA = opnStudentInfo.nextLine();
                    majoring.GPA = Double.parseDouble(strGPA);
                }
                
                // De-allocate the memory that was used by the scanner
                opnStudentInfo.close();
            }
            
            return majoring;
        }
        
        public static void show(Student std) throws Exception {
            System.out.println("Student Record");
            System.out.println("Student ID: " + std.StudentIdentificationNumber);
            System.out.println("First Name: " + std.FirstName);
            System.out.println("Last Name: " + std.LastName);
            System.out.println("Number of credits so far: " + std.CreditsSoFar);
            System.out.println("Grade point average: " + std.GPA);
        }
        
        public static void main(String[] args) throws Exception {
            String mainAnswer = "Q", answer = "N";
            Scanner scnr = new Scanner(System.in);
            
            System.out.println("State University");
            System.out.println("What do you want to do?");
            System.out.println("R - Register a student");
            System.out.println("V - View a student information");
            System.out.println("Q - Exit or Quit");
            System.out.print("Your Answer? ");
            mainAnswer = scnr.next();
            
            if( (mainAnswer.equals("r")) || (mainAnswer.equals("R")) ) {
                Student std = register();
                
                System.out.print("Do you want to save this information (y/n)? ");
                answer = scnr.next();
                if( (answer.equals("y")) || (answer.equals("Y")) ) {
                    show(std);
                    save(std);
                }
            }
            else if( (mainAnswer.equals("v")) || (mainAnswer.equals("V")) ) {
                Student std = open();
                show(std);
            }
            else
                System.out.println("Good Bye!!!");
        }
    }
  2. Execute the application
  3. On the menu, indicate that you want to view a student record
  4. Enter one of the student file names and press Enter

File Management

 

Checking the Existence of a File

Besides writing to a file or reading from it, there are many other actions you may to perform on a file.

If you try opening a file that does not exist, you would receive an error:

Exception in thread "main" java.io.FileNotFoundException: Example1.xpl (The system 
cannot find the file specified)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.<init>(Unknown Source)
        at java.util.Scanner.<init>(Unknown Source)
        at Exercise.main(Exercise.java:9)

Therefore, before opening a file, you may want to check first whether it exists. To assist you with this, the File class is equipped with the exists() method. Here is an example of calling it:

import java.io.File;
import java.util.Scanner;

public class Exercise {
    public static void main(String[] args)  throws Exception {
	// Indicate that you are planning to opena file
	File fleExample = new File("Example1.xpl");
        
        // Find out if the file exists already
        if( fleExample.exists() ) {
	    // Prepare a Scanner that will "scan" the document
            Scanner opnScanner = new Scanner(fleExample);
	    // Read each line in the file
            while( opnScanner.hasNext() ) {
		// Read each line and display its value
	    	System.out.println("First Name:    " + opnScanner.nextLine());
	    	System.out.println("Last Name:     " + opnScanner.nextLine());
	    	System.out.println("Hourly Salary: " + opnScanner.nextLine());
	    	System.out.println("Is Full Time?: " + opnScanner.nextLine());
	    }
	
	    // De-allocate the memory that was used by the scanner
            opnScanner.close();   
	}
        else // if( !fleExample.exists() )
            System.out.println("No file exists with that name");
             
    }
}

Deleting a File

To delete a file, you can call the delete() method of the File class.

 

 
   

Previous Copyright © 2009-2012, FunctionX, Inc. Home