Download presentation
Presentation is loading. Please wait.
1
Files and Streams CS 21a Chapter 11 of Horstmann
2
10/02/05 Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved File Unit of “secondary” storage as opposed to “primary” storage in memory Stores a sequence of bytes/characters Associated with a filename Often organized under a directory hierarchy
3
10/02/05 Files Slide 3 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Text file A file containing text only A file you create in Notepad No special characters
4
10/02/05 Files Slide 4 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved What can you do with a text file? Create a text file Write to a text file Read from a text file Close a text file
5
10/02/05 Files Slide 5 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Important sequences To write to a text file 1. Create it. 2. Write to it (repeatedly). 3. Flush it (optional) 4. Close it. To read from a text file 1. Open it. 2. Read from it (repeatedly). 3. Close it Assumes the file exists.
6
10/02/05 Files Slide 6 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Writing to text files Create the text file PrintWriter f = new PrintWriter( “filename.txt” ); This opens the file. File is initially empty. Write to the text file f.println(…); // use like System.out Can be repeated. Close the file before exiting the program f.close(); // ensures contents are updated If you want to update the file without closing it yet, you can call f.flush();
7
10/02/05 Files Slide 7 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved 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(); Can be repeated. Close the text file in.close();
8
10/02/05 Files Slide 8 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved An example 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
9
10/02/05 Files Slide 9 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Our Java program 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
10
10/02/05 Files Slide 10 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved 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 ); 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 ); You need java.io.* for file ops and java.util.* for the Scanner class
11
10/02/05 Files Slide 11 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved 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 ); 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 ); This basically means ignore the errors for now (we’ll discuss them later)
12
10/02/05 Files Slide 12 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved 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 ); 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 ); Instantiates a Scanner to read input from the user
13
10/02/05 Files Slide 13 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved 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 ); 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 ); Gets the name of the input file from the user
14
10/02/05 Files Slide 14 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved 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 ); 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 ); Opens the input file
15
10/02/05 Files Slide 15 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved 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 ); 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 ); Creates a Scanner to read the file
16
10/02/05 Files Slide 16 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved 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 ); 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 ); Creates the output file
17
10/02/05 Files Slide 17 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved int lineNumber = 1; while( in.hasNextLine() ) { String line = in.nextLine(); out.println( "/* " + lineNumber + " */ " + line ); lineNumber++; } in.close(); out.close(); } Method that returns a true if the input file still has a at least one more line left to read.
18
10/02/05 Files Slide 18 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved int lineNumber = 1; while( in.hasNextLine() ) { String line = in.nextLine(); out.println( "/* " + lineNumber + " */ " + line ); lineNumber++; } in.close(); out.close(); } Reads one line from the input file
19
10/02/05 Files Slide 19 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved int lineNumber = 1; while( in.hasNextLine() ) { String line = in.nextLine(); out.println( "/* " + lineNumber + " */ " + line ); lineNumber++; } in.close(); out.close(); } Writes one line to the output file
20
10/02/05 Files Slide 20 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved int lineNumber = 1; while( in.hasNextLine() ) { String line = in.nextLine(); out.println( "/* " + lineNumber + " */ " + line ); lineNumber++; } in.close(); out.close(); } Closes the two files.
21
Exception handling
22
10/02/05 Files Slide 22 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Two main strategies Reporting Detecting that the error occurred Recovery Resumption of normal operations Exception handling passes control from point of error reporting to a competent recovery handler
23
10/02/05 Files Slide 23 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Categories of exceptions Checked 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 Unchecked Class will compile even without error handling Result from mistakes in programming E.g. all RuntimeException classes are unchecked
24
10/02/05 Files Slide 24 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Exceptions File operations throw exceptions Make sure statements are enclosed in a try- catch 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 use a try-catch chain to distinguish different exceptions Or, add throws IOException to the declaration of the method that uses files
25
10/02/05 Files Slide 25 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Example: Modified LineNumberer 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 ); Note: there is no more “throws Exception”
26
10/02/05 Files Slide 26 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Example: Modified LineNumberer 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 ); Try opening the file
27
10/02/05 Files Slide 27 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Example: Modified LineNumberer 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 ); If the open fails…
28
10/02/05 Files Slide 28 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved 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" ); }
29
10/02/05 Files Slide 29 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Try-catch Chain 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 … } … You can use a “try-catch chain” to catch specific exceptions AND / OR, you can catch IOException to catch any kind of IOException
30
10/02/05 Files Slide 30 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved The “finally” clause Used when an action needs to be performed whether or not an error occurred try { writeData( out ); } finally { out.close(); }
31
10/02/05 Files Slide 31 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved 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 }
32
10/02/05 Files Slide 32 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Exercises 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
33
More Exercises on Files and Streams
34
10/02/05 Files Slide 34 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Part1: The Basics 1. Write a program that prints your favorite poem to a file called "poem.txt" in the current directory. 2. 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. 3. 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
35
10/02/05 Files Slide 35 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Part2: String Manipulation 1. Find out what happens when you try to read a file that does not exist. 2. Find out what happens when you try to read more lines from a file than it actually has. 3. 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". 4. 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. 5. Write a program that prints out the first line of a file in reverse that is, abcd should become dcba.
36
10/02/05 Files Slide 36 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Part 3: Reading all lines from a File 1. Print out all the lines in "song.txt" as is. 2. Print out all the lines in "song.txt", but convert them to lowercase letters. 3. Print out all the lines in "song.txt", but in reverse order. The last line, should be printed first, and so on. 4. Print out every other line of "song.txt". 5. Given several filenames as arguments to your Java program (remember the args[] array?), print out all of their contents.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.