Chapter 16 - Files and Streams
Chapter 16 - Files and Streams
Chapter 16 - Files and Streams
Streams
Goals
To be able to read and write text files
To become familiar with the concepts of text
and binary formats
To learn about encryption
To understand when to use sequential and
random file access
To be able to read and write objects using
serialization
keyboard
standard
input stream
CPU
standard
output MEM
monitor stream
terminal
console
HDD
What does information
travel across?
Streams
keyboard
standard
input stream
CPU
standard
output MEM
monitor stream
terminal file
console input
stream
LOAD HDD
What does information READ
travel across? file
files output
Streams
stream
SAVE
WRITE
Reading and Writing Text Files
Text files – files containing simple text
Created with editors such as notepad, html, etc.
First way:
Use nextInt()
int number = scanner.nextInt();
Second way:
Use nextLine(), Integer.parseInt()
String input = scanner.nextLine();
int number = Integer.parseInt(input);
Numerical Input
Exceptions
nextInt() throws InputMismatchException
parseInt() throws NumberFormatException
Optimal use
nextInt() when there is multiple information on
one line
nextLine() + parseInt() when one number
per line
Reading Files
The same applies for both console input and
file input
Constructors
File(<full path>)
File(<path>, <filename>)
Methods
exists()
canRead(), canWrite()
isFile(), isDirectory()
File Class
java.io.FileReader
Associated with File object
Translates data bytes from File object into a
stream of characters (much like InputStream vs.
InputStreamReader)
Constructors
FileReader( <File object> );
Methods
read(), readLine()
close()
Writing to a File
We will use a PrintWriter object to write to a
file
What if file already exists? Empty file
Doesn’t exist? Create empty file with that name
fout.close();
Closing a File
Why?
When you call print() and/or println(), the
output is actually written to a buffer. When you
close or flush the output, the buffer is written to
the file
The slowest part of the computer is hard drive
operations – much more efficient to write once
instead of writing repeated times
File Locations
When determining a file name, the default is to
place in the same directory as your .class files
If we want to define other place, use an
absolute path (e.g. c:\My Documents)
in = new
FileReader(“c:\\homework\\input.dat”);
Why \\ ?
Sample Program
Two things to notice:
Have to import from java.io
I/O requires us to catch checked exceptions
java.io.IOException
Java Input Review
CONSOLE:
FILE:
FILE:
PrintWriter fout =
new PrintWriter(new File("output.txt");
fout.print("To a file");
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
try{
FileReader reader = new FileReader(inFile);
Scanner in = new Scanner(reader);
PrintWriter out = new
PrintWriter(outputFileName);
int lineNumber = 1;
while (in.hasNextLine()){
String line = in.nextLine();
out.println("/* " + lineNumber + " */ " +
line);
lineNumber++;
}
out.close();
} catch (IOException exception){
System.out.println("Error processing file: "
+ exception);
}
}
}
An Encryption Program
Demonstration: Use encryption to show file
techniques
File encryption
To scramble a file so that it is readable only to
those who know the encryption method and secret
keyword
(Big area of CS in terms of commercial
applications – biometrics, 128-bit encryption
breaking, etc.)
Modifications of Output
Two constraints so far:
Files are overwritten
Output is buffered and not written immediately
Constructors
FileWriter( <filename>, <boolean> );
true to append data, false to overwrite all of file
Methods
print(), println(): buffers data to write
flush(): sends buffered output to destination
close(): flushes and closes stream
Java File Output
// With append to an existing file
PrintWriter outFile1 =
new PrintWriter(
new FileWriter(dstFileName,true),false);
Disadvantage
Less efficient – writing to file takes up time, more
efficient to flush once (on close)
Caeser Cipher
Encryption key – the function to change the
value
BankAccount b = . . .;
out.writeObject(b);
Read in an object
readObject returns an Object reference
Need to remember the types of the objects that
you saved and use a cast
ObjectInputStream in = new
ObjectInputStream( new
FileInputStream("bank.dat"));
BankAccount b = (BankAccount) in.readObject();
Exceptions
readObject method can throw a
ClassNotFoundException
It is a checked exception
Constructors
StringTokenizer(String line)//default dlms
StringTokenizer(String ln, String dlms)
Methods
hasMoreTokens()
nextToken()
countTokens()
StringTokenizing in Java
Scanner stdin = new…
System.out.print( "Enter a line with comma
seperated integers(no space): " );
String input = stdin.nextLine();
StringTokenizer st;
String delims = ",";
st = new StringTokenizer( input, delims );
while ( st.hasMoreTokens() )
{
int n = Integer.parseInt(st.nextToken());
System.out.println(n);
}
File gradeFile = new File(“scores.txt”);
if(gradeFile.exists()){
Scanner inFile = new Scanner(gradeFile);
while(line != null){
StringTokenizer st = new
StringTokenizer(line, ":");
System.out.print(" Name: " + st.nextToken());
int num = 0;
double sum = 0;
while ( st.hasMoreTokens() )
{
num++;
sum += Integer.parseInt(st.nextToken());
}
System.our.println(" average = "+ sum/num);
line = inFile.nextLine();
}
inFile.close();
}