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. 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();
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.*; public class NumberLines
{ |
import java.io.*; public class
NumberLines2 { //in
red: the code common to both versions
|
OUTPUT (for both versions) |
For the text.txt file |
1 abcdefghijklmnoprstuvxyz |
abcdefghijklmnoprstuvxyz |
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
- PrintStream outputStreamName;
- outputStreamName = new PrintStream(new File(FileName));
- The file should be opened inside a try block
- A catch block should catch and handle the possible exception
- Note: The variable that refers to the PrintStream object (outputStreamName) should be declared outside the block (and initialized to null).
Version #1(try/catch) |
Version #2(try/catch/finally) |
import java.io.*; public class
FileOutput_1 {
|
import java.io.*; public class
FileOutput_2 { |
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.*; public class MaxOfTwo {
try { |
import java.io.*; public class
MaxOfTwo2 { //in
red: the code common to both versionss
|
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 public class AvgOf_MAX {
try { |
import java.io.*; // for File, FileNotFoundException public class
AvgOf_MAX2 {
while(inputFile.hasNext())
{ //in
red: the code common to both versions
|
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.*; public
class Temperatures {
try { |
import java.io.*; public class
Temperatures2 {
int temp1 = inputFile.nextInt();
//in
red: the code common to both versions
|
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.*; public class
Temperatures3 { |
import
java.io.*; public
class Temperatures4 { fileName = input.nextLine();
|
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