File Input and Output
File Input and Output
Objectives
After you have read and studied this chapter, you should
be able to
Use File object to get info about a file
Include a JFileChooser object in your program to let the user
specify a file.
Write bytes to a file and read them back from the file, using
FileOutputStream and FileInputStream.
Write values of primitive data types to a file and read them back
from the file, using DataOutputStream and DataInputStream.
Write text data to a file and read them back from the file, using
FileWriter,PrintWriter and FileReader,BufferedReader
Read a text file using Scanner
File
Creates
CreatesFile
Fileobject
object for
for
File inFile = new File(sample.dat); the
the file sample.dat inthe
file sample.dat in the
current directory.
current directory.
if ( inFile.isFile() ) { ToTosee
seeififinFile
inFileisis
associated
associatedtotoaafile. file.IfIf
false,
false,ititisisaadirectory.
directory.
if ( inFile.isDirectory() ) { Also,
Also, can testdirectly
can test directlyififitit
isisaadirectory.
directory.
if ( inFile.getName() ) { To
Toget
getthe
thename
nameofofthe
the
file represented by inFile
file represented by inFile
To
Tosee
seeififinFile
inFileisis
if ( inFile.canRead() ) {
associated
associatedtotoaafilefilethat
that
exist & can be read
exist & can be read
To
Tosee
seeififinFile
inFileisis
if ( inFile.canWrite() ) {
associated
associatedtotoaafilefilethat
that
exist & can be written
exist & can be written
The JFileChooser Class
chooser.showOpenDialog(null);
chooser.showOpenDialog(null);
The JFileChooser Class
Getting Info from JFileChooser
IO class
Hierarchy
in java.io
package
Streams for Byte level Binary File I/O
FileOutputStream
outStream = new FileOutputStream( outFile );
//data to save
byte[] byteArray = {10, 20, 30, 40,
50, 60, 70, 80};
import java.io.*;
class Ch12TestDataOutputStream {
public static void main (String[] args) throws IOException {
. . . //set up outDataStream
import java.io.*;
class Ch12TestDataInputStream {
public static void main (String[] args) throws IOException {
. . . //set up inDataStream
str = bufReader.readLine();
int i = Integer.parseInt(str);
bufReader.close();
}
}
Sample Reading Textfile using Scanner
import java.io.*;
class Ch12TestScanner {
//get integer
int i = scanner.nextInt();
scanner.close();
}
}
Sample Reading Textfile using Scanner
Code fragments shows how to read the whole contents of a file
try{
// read line one by one till all line is read.
Scanner scanner = new Scanner(inFile);
while (scanner.hasNextLine()) { //check if there are more line
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}