File Input and Output
File Input and Output
File Input and Output
and Output
Objectives
After you have read and studied this chapter, you
should be able to
• Write bytes to a file and read them back from the file, using
FileOutputStream and FileInputStream.
• Write text data to a file and read them back from the file, using
FileWriter,PrintWriter and FileReader,BufferedReader
A binary file
contains bytes that represent other format (eg.
numbers, image, audio, formatted text etc)
java file class
File class in java is from java.io
• To use, we must first create a file object
• A file object can represent a file or a directory
JFileChooser chooser =
To start the
new JFileChooser("D:/JavaPrograms/Ch12"); listing from a
specific
directory
chooser.showOpenDialog(null);
using JFileChooser
IO class
Hierarchy
in java.io
package
FileOutputStream FileInputStream
for output a allows us to
sequence of bytes ( read in an
data of type byte) array of bytes.
sample: byte-level binary file output
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();
}