Transcript Files

Files and Streams
CS 21a
Chapter 11 of Horstmann
File

Unit of “secondary” storage




10/02/05
as opposed to “primary” storage in memory
Stores a sequence of bytes/characters
Associated with a filename
Often organized under a directory
hierarchy
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 2
Text file

A file containing text only


10/02/05
A file you create in Notepad
No special characters
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 3
What can you do with a text file?




10/02/05
Create a text file
Write to a text file
Read from a text file
Close a text file
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 4
Important sequences

To write to a text
file
1.
2.
3.
4.
10/02/05
Create it.
Write to it
(repeatedly).
Flush it (optional)
Close it.

To read from a text
file
1.
2.
3.

Open it.
Read from it
(repeatedly).
Close it
Assumes the file
exists.
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 5
Writing to text files

Create the text file




Write to the text file



10/02/05
f.println(…); // use like System.out
Can be repeated.
Close the file before exiting the program


PrintWriter f = new PrintWriter( “filename.txt” );
This opens the file.
File is initially empty.
f.close(); // ensures contents are updated
If you want to update the file without closing it
yet, you can call f.flush();
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 6
Reading from a text file

Open the text file



FileReader reader = new FileReader(
“file.txt”)
Scanner in = new Scanner( reader )
Read from the text file

String line = in.nextLine();


Close the text file

10/02/05
Can be repeated.
in.close();
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 7
An example


10/02/05
Using a text editor such as Notepad,
create a file with the following contents:
Bahay kubo
kahit munti
ang halaman doon
ay sari-sari
Save it as bahay.txt
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 8
Our Java program



10/02/05
Reads the contents of “bahay.txt”
Numbers each line and writes it to
another file
Expected output:a file with contents as
follows:
/* 1 */ Bahay kubo
/* 2 */ kahit munti
/* 3 */ ang halaman doon
/* 4 */ ay sari-sari
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 9
Program LineNumberer.java
import java.io.*;
import java.util.*;
You need java.io.* for file ops
and java.util.* for the Scanner
class
public class LineNumberer
{
public static void main( String args[])
throws FileNotFoundException
{
Scanner console = new Scanner( System.in );
System.out.println( "Input file: " );
String inputFileName = console.next();
System.out.println( "Output file: " );
String outputFileName = console.next();
FileReader reader = new FileReader( inputFileName );
Scanner in = new Scanner( reader );
PrintWriter out = new PrintWriter( outputFileName );
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 10
Program LineNumberer.java
import java.io.*;
import java.util.*;
This basically means ignore the
errors for now (we’ll discuss them
later)
public class LineNumberer
{
public static void main( String args[])
throws FileNotFoundException
{
Scanner console = new Scanner( System.in );
System.out.println( "Input file: " );
String inputFileName = console.next();
System.out.println( "Output file: " );
String outputFileName = console.next();
FileReader reader = new FileReader( inputFileName );
Scanner in = new Scanner( reader );
PrintWriter out = new PrintWriter( outputFileName );
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 11
Program LineNumberer.java
import java.io.*;
import java.util.*;
Instantiates a Scanner to read
input from the user
public class LineNumberer
{
public static void main( String args[])
throws FileNotFoundException
{
Scanner console = new Scanner( System.in );
System.out.println( "Input file: " );
String inputFileName = console.next();
System.out.println( "Output file: " );
String outputFileName = console.next();
FileReader reader = new FileReader( inputFileName );
Scanner in = new Scanner( reader );
PrintWriter out = new PrintWriter( outputFileName );
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 12
Program LineNumberer.java
import java.io.*;
import java.util.*;
public class LineNumberer
Gets the name of the
{
input file from the user
public static void main( String args[])
throws FileNotFoundException
{
Scanner console = new Scanner( System.in );
System.out.println( "Input file: " );
String inputFileName = console.next();
System.out.println( "Output file: " );
String outputFileName = console.next();
FileReader reader = new FileReader( inputFileName );
Scanner in = new Scanner( reader );
PrintWriter out = new PrintWriter( outputFileName );
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 13
Program LineNumberer.java
import java.io.*;
import java.util.*;
public class LineNumberer
{
public static void main( String args[])
throws FileNotFoundException
Opens the input file
{
Scanner console = new Scanner( System.in );
System.out.println( "Input file: " );
String inputFileName = console.next();
System.out.println( "Output file: " );
String outputFileName = console.next();
FileReader reader = new FileReader( inputFileName );
Scanner in = new Scanner( reader );
PrintWriter out = new PrintWriter( outputFileName );
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 14
Program LineNumberer.java
import java.io.*;
import java.util.*;
public class LineNumberer
{
public static void main( String args[])
throws FileNotFoundException
Creates a Scanner
{
to read the file
Scanner console = new Scanner( System.in );
System.out.println( "Input file: " );
String inputFileName = console.next();
System.out.println( "Output file: " );
String outputFileName = console.next();
FileReader reader = new FileReader( inputFileName );
Scanner in = new Scanner( reader );
PrintWriter out = new PrintWriter( outputFileName );
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 15
Program LineNumberer.java
import java.io.*;
import java.util.*;
public class LineNumberer
{
public static void main( String args[])
throws FileNotFoundException
{
Scanner console = new Scanner( System.in ); Creates the
System.out.println( "Input file: " );
output file
String inputFileName = console.next();
System.out.println( "Output file: " );
String outputFileName = console.next();
FileReader reader = new FileReader( inputFileName );
Scanner in = new Scanner( reader );
PrintWriter out = new PrintWriter( outputFileName );
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 16
int lineNumber = 1;
while( in.hasNextLine() ) {
String line = in.nextLine();
out.println( "/* " + lineNumber + " */ " +
line );
lineNumber++;
Method that returns a true
}
if the input file still has a
at least one more line left
in.close();
to read.
out.close();
}
}
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 17
int lineNumber = 1;
while( in.hasNextLine() ) {
String line = in.nextLine();
out.println( "/* " + lineNumber + " */ " +
line );
lineNumber++;
Reads one line from the
}
input file
in.close();
out.close();
}
}
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 18
int lineNumber = 1;
while( in.hasNextLine() ) {
String line = in.nextLine();
out.println( "/* " + lineNumber + " */ " +
line );
lineNumber++;
}
in.close();
Writes one line to the
out.close();
output file
}
}
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 19
int lineNumber = 1;
while( in.hasNextLine() ) {
String line = in.nextLine();
out.println( "/* " + lineNumber + " */ " +
line );
lineNumber++;
}
in.close();
Closes the two files.
out.close();
}
}
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 20
Exception handling
Two main strategies

Reporting


Recovery


10/02/05
Detecting that the error occurred
Resumption of normal operations
Exception handling passes control from
point of error reporting to a competent
recovery handler
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 22
Categories of exceptions

Checked





Unchecked



10/02/05
At compile time, the compiler requires you to
address these errors
Likely to happen no matter how careful you are in
coding
Class will not compile if you have no error handling
E.g. all classes of IOException are checked
Class will compile even without error handling
Result from mistakes in programming
E.g. all RuntimeException classes are unchecked
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 23
Exceptions


File operations throw exceptions
Make sure statements are enclosed in a trycatch statement


if you look at Java docs, you will see that the file
I/O methods say “throws IOException”
this means that the compiler will require you to
catch IOException


10/02/05
use a try-catch chain to distinguish different exceptions
Or, add throws IOException to the declaration
of the method that uses files
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 24
Example: Modified LineNumberer
Note: there is no more
“throws Exception”
public static void main( String args[])
{
Scanner console = new Scanner( System.in );
boolean fileFound;
FileReader reader = null;
do {
System.out.println( "Input file: " );
String inputFileName = console.next();
fileFound = true;
try {
reader = new FileReader( inputFileName );
}
catch ( FileNotFoundException f ) {
fileFound = false;
System.out.println( "Not found!" );
}
} while ( !fileFound );
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 25
Example: Modified LineNumberer
public static void main( String args[])
{
Scanner console = new Scanner( System.in );
boolean fileFound;
Try opening the
FileReader reader = null;
do {
System.out.println( "Input file: " );
String inputFileName = console.next();
fileFound = true;
try {
reader = new FileReader( inputFileName );
}
catch ( FileNotFoundException f ) {
fileFound = false;
System.out.println( "Not found!" );
}
} while ( !fileFound );
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
file
Files
Slide 26
Example: Modified LineNumberer
public static void main( String args[])
{
Scanner console = new Scanner( System.in );
boolean fileFound;
If the open fails…
FileReader reader = null;
do {
System.out.println( "Input file: " );
String inputFileName = console.next();
fileFound = true;
try {
reader = new FileReader( inputFileName );
}
catch ( FileNotFoundException f ) {
fileFound = false;
System.out.println( "Not found!" );
}
} while ( !fileFound );
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 27
Example: Modified LineNumberer


You have to write a similar try-catch block for the output file.
Con’t of the code:
Scanner in = new Scanner( reader );
System.out.println( "Output file: " );
String outputFileName = console.next();
PrintWriter out = null;
try {
out = new PrintWriter( outputFileName );
}
catch ( FileNotFoundException f ) {
System.out.println( "File not opened" );
}
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 28
Try-catch Chain


10/02/05
You can use a
“try-catch chain”
to catch specific
exceptions
AND / OR,
you can catch
IOException
to catch any kind
of IOException
try
{ … file operations …
}
catch( FileNotFoundException se )
{ … if file is not found …
}
catch( EOFException ee )
{ … if no more data to read …
}
catch( IOException e )
{ … for all other cases not yet
covered …
}
…
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 29
The “finally” clause

10/02/05
Used when an action needs to be
performed whether or not an error
occurred
try {
writeData( out );
}
finally {
out.close();
}
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 30
Throwing exceptions


If you choose not to catch exceptions,
you must declare that they will be thrown
This means when a file-related exception
does occur, a run-time error will result
public static void main( String args[] )
throws IOException
{
… file operations not
enclosed in a try-catch
statement
}
10/02/05
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 31
Exercises


10/02/05
Do a “Hello World” program that writes
to a text file instead of the screen
Write a “Type” program that prints out
the contents of any text file (given as a
command-line parameter) to the screen
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 32
More Exercises on Files and Streams
Part1: The Basics
1.
2.
3.
10/02/05
Write a program that prints your favorite poem to a
file called "poem.txt" in the current directory.
Write a program that prints the lyrics of the 12 days
of Christmas to "12days.txt". Use a loop so that you
don't actually have to write a gazillion print
statements.
Write a program that reads a line from the user
(remember JOptionPane.showInputDialog?) to a text
file called "chat.txt". The program should not
overwrite the text file each time you call it, but only
add it to the end. Hint: search on the Internet or
check out the JDK documentation for FileWriter
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 34
Part2: String Manipulation
1.
2.
3.
4.
5.
10/02/05
Find out what happens when you try to read a file that does not
exist.
Find out what happens when you try to read more lines from a file
than it actually has.
If you don't have a file called "poem.txt" yet, use Notepad to
create it. Make sure it has at least three lines. Write a program
that displays the first three lines of "poem.txt".
If you don't have a file called "poem.txt" yet, use Notepad to
create it. Make sure it has at least three lines. Write a program
that displays the first three lines of "poem.txt" in reverse order the third line, then the second line, then the first.
Write a program that prints out the first line of a file in reverse
that is, abcd should become dcba.
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 35
Part 3: Reading all lines from a File
1.
2.
3.
4.
5.
10/02/05
Print out all the lines in "song.txt" as is.
Print out all the lines in "song.txt", but convert them
to lowercase letters.
Print out all the lines in "song.txt", but in reverse
order. The last line, should be printed first, and so on.
Print out every other line of "song.txt".
Given several filenames as arguments to your Java
program (remember the args[] array?), print out all of
their contents.
Copyright 2005, by the authors of these slides, and Ateneo de Manila
University. All rights reserved
Files
Slide 36