Chapter 5
Chapter 5
Java can read several types of information from files: binary, Java objects, text, zipped
files, etc. The most common types of files are:
Text Files
Classes Descriptions
1. To open a file, make a File or FileReader input object and link it with an
external existing file name:
infile.close();
import java.io.*;
in.close();
} // end try
catch(FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
catch(EOFException eof) {
System.out.println(eof.getMessage());
}
catch(IOException io) {
System.out.println(io.getMessage());
}
} // end main
} // end class
For Java 5.0, the Scanner class can be used for text input, which is more convenient.
It is a simple text scanner which can parse primitive types and strings using regular
expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default
matches whitespace. The resulting tokens may then be converted into values of different
types using the various next methods.
Classes Descriptions
Sample Program:
in.close();
import java.io.*;
import java.util.*;
while (in.hasNextLine())
{
name = in.next();
score = in.nextFloat();
total += score;
System.out.println(" Name: " + name + "Score: " +
score);
}
in.close();
} // end try
catch(IOException io) {
System.out.println(io.getMessage());
}
}
}
Classes Descriptions
Steps:
1. Make a File or FileWriter output object to link it with an external file name:
outfile.close();
import java.io.*;
import javax.swing.*;
} // end for
// close the files to make sure that all output are written to the files
out1.close();
out2.close();
}//end try
catch(FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
catch(EOFException eof) {
System.out.println(eof.getMessage());
}
catch(IOException io) {
System.out.println(io.getMessage());
}
catch(Exception nf) {
System.out.println(nf.getMessage());
}
} // end main
} // end class
in.close();
out.close();
} // end try
catch(FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
catch(EOFException eof) {
System.out.println(eof.getMessage());
}
catch(IOException io) {
System.out.println(io.getMessage());
}
}// end main
}// end classFileInputOutput
import java.io.*;
import javax.swing.*;
import java.util.*;
try
{
FileReader reader = new FileReader(inFile);
BufferedReader in = new BufferedReader(reader);
total += score;
out.println("Name: " + name + " Score: " + score + "
Grade:" + grade);
}
} // end try
catch(FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
catch(EOFException eof) {
System.out.println(eof.getMessage());
}
catch(IOException io) {
System.out.println(io.getMessage());
}
}
}
http://java.sun.com