Vous êtes sur la page 1sur 14

File Processing

les

troduction

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

port java.io.File;

blic class Exercise {


public static void main(String[] args)

throws Exception {

he File class
is
based
on
(implements)
the FileOutputStream class.
he FileOutputStreamclass is based on the OutputStream class. That is how it gets most of its
unctionality.

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

port java.io.File;

blic class Exercise {


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

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

Practical 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;
}

eating a File

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

port java.io.PrintWriter;

blic class Exercise {


public static void main(String[] args)

throws Exception {

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

efore using the class, declare a variable for it. This class is equipped with many constructors. One
f the constructors takes as argument an OutputStream object. We saw that the File class is
ased on OutputStream. This means that you can pass a File object to a PrintWriterconstructor.
his would be done as follows:

port java.io.File;
port java.io.PrintWriter;

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

riting to a File

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

port java.io.File;
port java.io.PrintWriter;

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

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

port java.io.File;
port java.io.PrintWriter;

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

it

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

pening a File

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

port java.io.File;

blic class Exercise {


public static void main(String[] args) throws Exception {
// Incidate that you are planning to opena file

File fleExample = new File("Example.xpl");


}

eading From a File

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

port java.io.File;
port java.util.Scanner;

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

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

port java.io.File;
port java.util.Scanner;

blic 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());
}

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

port java.io.File;
port java.util.Scanner;

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

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;

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();
(y/n)? ");

System.out.print("Do you want to save this information

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

le Management

hecking the Existence of a File

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

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

ception in thread "main" java.io.FileNotFoundException: Example1.xpl (The system

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

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

port java.io.File;
port java.util.Scanner;

blic 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");
}

eleting a File

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