Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lesson 8: More File I/O February 5, 2008

Similar presentations


Presentation on theme: "Lesson 8: More File I/O February 5, 2008"— Presentation transcript:

1 Lesson 8: More File I/O February 5, 2008

2 Streams and File I/O Types of Streams
Reading from and Writing to Streams File Input File class Scanner File Output BufferedWriter w/ FileWriter PrintWriter Will also get our first look at exceptions and how to catch and handle them.

3 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(); Look at FileReader constructor in the API Look at File class in the API

4 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

5 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

6 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”);

7 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

8 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); } 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();

9 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); } 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();

10 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.

11 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

12 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

13 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 Must close the output file in order to flush the data that has been buffered!

14 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 PrintStream javadocs: All characters printed by a PrintStream are converted into bytes using the platform's default character encoding. The PrintWriter class should be used in situations that require writing characters rather than bytes. Neither PrintStream nor PrintWriter throw the IOExceptions therefore they don’t need to be caught. See PrintStream javadoc Must flush output buffers

15 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


Download ppt "Lesson 8: More File I/O February 5, 2008"

Similar presentations


Ads by Google