Download Object-Oriented S/W Development with Java CSCI 3381 The File

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Object-Oriented S/W Development with Java CSCI 3381
Lesson 8:
More File I/O
February 5, 2008
Object-Oriented S/W Development with Java CSCI 3381
Streams and File I/O
 Types
of Streams
 Reading from and Writing to Streams
 File Input
 File
class
 Scanner
 File
Output
 BufferedWriter
 PrintWriter
w/ FileWriter
Object-Oriented S/W Development with Java CSCI 3381
The File Class
FileReader can also be instantiated with a File
object.
 The File class is used to represent the path to the file.
The name of the class is misleading. The File class is
really a path manager where the path can be to a file, or
to a directory (a set of files).

File inputFile = new File(“inputFile.txt”);
BufferedReader br;
br = new BufferedReader(new
FileReader(inputFile));
String input = br.readLine();
Object-Oriented S/W Development with Java CSCI 3381
The File Class (cont.)
Call to File class constructor doesn’t create a file
with specified filename
 Creating a file from a File object is done with
createNewFile method in File class




Example: File myFile;
myFile.createNewFile(“input.txt”);
Creates new, empty file “input.txt” if it doesn’t already exist
and associates it with myFile File object
Can use exists method in File class to tell you
whether file exists with name specified
Object-Oriented S/W Development with Java CSCI 3381
Representing Directories with File Class
A File object can represent either a file or a
directory.
 Use isDirectory and isFile methods to tell
whether the File object represents a directory or a
file
 If File object represents a directory, you can use the
list method to get an array of fileames in that
directory

Object-Oriented S/W Development with Java CSCI 3381
Avoiding File System Dependencies

Use File objects rather than strings when manipulating file or
directory names to avoid system dependencies associated with
filenames

Use File class equals method to eliminate inconsistencies
caused by difference in case and file delimiter used on
different systems when comparing file names
Example:
File myFile(“myFile.txt”);
File yourFile(“yourFile.txt”);
if(myFile.equals(yourFile)
System.out.println(“Files are the same”);

Use File class separator instance field instead of / or \
(or other delimiter) when constructing file path names
Example:
File foo;
foo = new File(“Documents” + File.separator + “data.txt”);
Object-Oriented S/W Development with Java CSCI 3381
Avoiding File System Dependencies (cont.)

Use File method getCanonicalFile to return
canonical path name for file getCanonicalFile:



removes redundant “.” directories
provides correct directory separator for system being used
provides capitalization preferred by underlying system
Object-Oriented S/W Development with Java CSCI 3381
Revisiting InputDemo.java
import java.io.*;
import java.util.*;
public class InputDemo {
public InputDemo() { }
public void readFile() {
String studentID, first, last, major;
try {
FileReader inFile = new FileReader(“students.txt");
BufferedReader br = new BufferedReader(inFile);
String input;
input = br.readLine();
while (input != null) {
Scanner parser = new Scanner(input);
studentID = parser.next();
last = parser.next();
first = parser.next();
major = parser.nextLine();
System.out.println(first + ' ' + last + " ID#: " + studentID);
input = br.readLine();
}
}
catch (FileNotFoundException ex) {
System.out.println("File not found");
}
catch (IOException ex) {
System.out.println("Unable to read from file");
}
}
public static void main(String[] args) {
InputDemo id = new InputDemo();
id.readFile();
}
}
Object-Oriented S/W Development with Java CSCI 3381
InputDemo.java using File class
import java.io.*;
import java.util.*;
public class InputDemo {
public InputDemo() { }
public void readFile() {
String studentID, first, last, major;
try {
File inFile = new File(“students.txt”);
FileReader inf = new FileReader(inFile);
BufferedReader br = new BufferedReader(inf);
String input;
input = br.readLine();
while (input != null) {
Scanner parser = new Scanner(input);
studentID = parser.next();
last = parser.next();
first = parser.next();
major = parser.nextLine();
System.out.println(first + ' ' + last + " ID#: " + studentID);
input = br.readLine();
}
}
catch (FileNotFoundException ex) {
System.out.println("File not found");
}
catch (IOException ex) {
System.out.println("Unable to read from file");
}
}
public static void main(String[] args) {
InputDemo id = new InputDemo();
id.readFile();
}
Object-Oriented S/W Development with Java CSCI 3381
Scanner

Scanners are very versatile and can be wrapped
around many different streams to process input:

Strings
• Saw this when we parsed the input in the previous example
(InputDemo.java)

InputStreams
• System.in - We’ve already seen this one

Readers, i.e., FileReader
• Very similar to the previous example except the Scanner takes the
place of the BufferedReader
• Scanner and BufferedReader provide different methods and
functionality. See the JavaDocs.

File objects – Scanner can be wrapped directly around
File objects. In other words, it takes the place of the
FileReader and the BufferedReader.
Object-Oriented S/W Development with Java CSCI 3381
File Input Using
Scanner with a File object

Reading from a file with a Scanner
File myInputFile = new File(“inputFile.txt”);
Scanner inputScanner = new Scanner(myInputFile);
String input = inputScanner.nextLine();

Just like with a BufferedReader:

Must explicitly handle the possible i/o errors (Exceptions)
• FileNotFoundException only



Close the stream…inputScanner.close()
May need to parse input using another Scanner
Scanner Example: InputDemoScanner.java
Object-Oriented S/W Development with Java CSCI 3381
File Output
 Next,
we’ll look at two methods for writing
to a file:
 using
a BufferedWriter with the FileWriter class
 using the PrintWriter class
Object-Oriented S/W Development with Java CSCI 3381
File Output Using
BufferedWriter with FileWriter



Instead of sending our output to the console, we’ll write it to a
file.
Very similar to File Reader and BufferedReader.
Writing to a file with a BufferedWriter
BufferedWriter bw;
bw = new BufferedWriter (new
FileWriter(“outputFile.txt”));
outputFile.write(“Here is a string”);
outputFile.newLine();



Need to explicitly handle the possible i/o errors
(Exceptions)
Don’t forget to close the stream…bw.close()
BufferedWriter Example: OutputDemo.java
Object-Oriented S/W Development with Java CSCI 3381
File Output Using PrintWriter

PrintWriter constructors





OutputStream, i.e., FileOutputStream or
ObjectOutputStream
Writers
String, i.e., “outputFile.txt”
File Object
Writing to a file with PrintWriter (see also PrintStream)
File outputFile = new File("outputFile.txt");
PrintWriter output = new PrintWriter(outputFile);
output.println("Scanner read following input: " + input);
output.printf(…);

Need to explicitly handle the possible errors (Exceptions)



FileNotFoundException only
Don’t forget to close the stream…output.close()
PrintWriter Example: OutputDemoPrint.java
Object-Oriented S/W Development with Java CSCI 3381
Punch Line
Pick a way to read from and write to a file and stick
with it for now.
 My recommendation



File input: use the Scanner with a File object
File output: use the PrintWriter with a File object