Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.

Similar presentations


Presentation on theme: "Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105."— Presentation transcript:

1 Chapter 91 Streams and File I/O Chapter 9

2 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105 –Chapters 5–9 Discussion group after Spring Break –Monday, B155, 7:00 – 9:00pm –Exam review!

3 3 File I/O Why bother? Persistent storage  Use over multiple sessions  Safety In case of failure (program, computer) What are files? Collections of bytes  Can be abstracted and viewed otherwise Different Types?

4 4 Streams All file I/O is treated like a stream  Moving flow of data Different classes can work with the stream –Provide filters and abstractions –Like an assembly line for data File FileInputStrea m Lots of data DataInputStream bytes int char boolean double String

5 5 Streams A stream can only flow in one direction.  Need input streams and output streams Useful classes: General File String (split) JFileChooser Input FileInputStream DataInputStream ObjectInputStream FileReader BufferedReader Scanner Output FileOutputStream DataOutputStream ObjectOutputStream (FileWriter) PrintWriter

6 Chapter 96 Text Files and Binary Files All data in a file is stored as binary digits. –Files with contents that must be treated as sequences of binary digits are called binary files; binary files can be read only by machines.

7 Chapter 97 Text Files and Binary Files, cont. Sometimes, it is more convenient to think of a file’s contents as a sequence of characters. –Files with streams and methods to make them look like sequences of characters are called text files; text files can be read by people.

8 Chapter 98 Text Files and Binary Files, cont. However, binary files are more efficient to process than text files. In Java, binary files are platform- independent. –Binary files can be created by one computer and read by another, combining portability and efficiency.

9 Chapter 99 Text Files and Binary Files, cont. Though text files can be read and written using an editor, binary files must be read and written by a program.

10 10 Example 1 What does the following program do? try { String in = "in.txt"; int numLines = 5; BufferedReader reader = new BufferedReader( new FileReader( in ) ); for ( int line = 0; line < numLines; ++line ) { System.out.println( reader.readLine() ); } } catch( IOException ioe ) { System.err.println( "Crush! Kill! Destroy!" ); } What if the number of lines is unknown? Is there anything missing?

11 11 Example 2 try { String in = "in.txt"; BufferedReader reader = new BufferedReader( new FileReader( in ) ); String line = reader.readLine(); while( null != line ) { System.out.println( reader.readLine() ); line = reader.readLine(); } } catch( IOException ioe ) { System.err.println( "I can't do that, Dave!" ); } But we still need to close it! Where? What changes when reading a byte at a time?

12 12 Example 3 BufferedReader reader = null; try {... } catch( IOException ioe ){... } finally { try { if ( null != reader ) reader.close(); } catch( IOException ioe ) { System.err.println( "Error closing file" ); } close() should almost always be called in a finally block! close() should almost always be called in a finally block!

13 13 Scanner Class import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException;... try { Scanner scanner = new Scanner( new File( “in.txt” ) ); while( scanner.hasNextLine() ) { System.out.println( scanner.nextLine() ); } } catch( FileNotFoundException e ) { System.err.println( "Unable to open file!" ); }

14 Chapter 914 Use toString for Text-File Output Classes typically include a method toString. The methods println and print in class PrintWriter behave like System.out.println and System.out.print, respectively.

15 15 Example - toString() PrintWriter writer = null; try { String outFile = "out.txt"; writer = new PrintWriter(new FileOutputStream(outFile)); Date today = new Date(); writer.println( today.toString() ); writer.println( "Today is " + today ); } catch( FileNotFoundException ioe ) { System.err.println( "Exterrrrrrminate!" ); } finally {...} Notice: toString() is part of any object

16 Chapter 916 StringTokenizer Class Class BufferedReader can read entire lines or single characters, but not single words. Class StringTokenizer can take an entire line of text and break it into individual words. The class StringTokenizer is in the java.util package. Individual words are called tokens.

17 Chapter 917 StringTokenizer example Tokens are nonwhitespace characters. StringTokenizer tokenizer = new StringTokenizer(“Read my lips!”) while (tokenizer.hasMoreTokens()) { System.out.println( tokenizer.nextToken() ); } produces Read my lips!

18 Chapter 918 StringTokenizer, cont'd Separators are whitespace characters unless otherwise specified. To specify a set of separators, a string consisting of all the separator characters is given as a second argument to the constructor. example … new StringTokenizer(“Read my lips!”, “\n.,!”);

19 Chapter 919 String.split() example StringTokenizer is a legacy class! – use String split() method String s = “Read my lips!” String[] tokens = s.split( “ “ ); for( String token : tokens ) { System.out.println( token ); } produces Read my lips! split() argument is the delimeter

20 Chapter 920 Using the File Class The methods of the class File can check the properties of files. –Does the named file exist? –Is the file readable? Typically, the operating systems lets you designate files as not readable or as readable only by certain users.

21 Chapter 921 Using the File Class, cont. The File class is like a wrapper class for strings which are file names. –example new File(“treasure.txt”)

22 Chapter 922 Some File Methods public boolean exists() public boolean canRead() public boolean canWrite() public boolean delete() public boolean length() public String getName() public String getPath() Can these be used to avoid exceptions?

23 23 Object I/O Object I/O can be binary ObjectInputStream and ObjectOutputStream ObjectOutputStream oos = new ObjectOutputStream new FileOutputStream( ) ); oos.writeObject( new Date() );... ObjectInputStream ois = new ObjectInputStream new FileInputStream( ) ); Date aDate = (Date)ois.readObject();

24 Chapter 924 Output to Binary Files Using ObjectOutputStream class BinaryOutputDemo

25 Chapter 925 The EOFException Class ObjectInputStream methods that read from a binary file throw an EOFException when they try to read beyond the end of the file. When using class ObjectInputStream, the class EOFException can test for the end of a file.

26 Chapter 926 EOFException Example Does the order you catch Exceptions matter?

27 Chapter 927 Checking for the End of File Different classes with file reading methods check for the end of a file in different ways. –Binary files throw an exception in the class EOFException. –A text file returns a special value, such as null. Be sure to test for the end of the file in the correct way.

28 28 Object Stream Concerns Could an instance of the following class be written: public class SomeClass { String aString = “someText”; } Why or why not?

29 29 Object Stream Concerns Any object serialized by a stream must implement Serializable - Acts as a marker for what can be written public class SomeClass implements Serializable { String aString = “someText”; }

30 Chapter 930 The Serializable Interface A class which is serializable affects how Java performs file I/O with objects of the class. –Java assigns a serial number to each object of the class that it writes to a stream of type ObjectOutputStream. –If the object is written more than once, Java writes only the serial number for the object.

31 Chapter 931 Array Objects in Binary Files An entire array can be saved to a binary file using objectWrite, and can be read later using objectRead. If the base type of the array is a class, the class should be serializable. All the data in an array can be outputted to a binary file using a single invocation of objectWrite.

32 Chapter 932 (optional) Graphics Supplement Programming Example: A JFrame GUI for Manipulating Files –Accept a file and display its first line. –Provide an explanatory message if the file does not exist or is unreadable. –Delete a selected file. –Provide an explanatory message if the file does not exist or is unwriteable (and hence cannot be deleted).

33 Chapter 933 Graphics Supplement class FileOrganizer

34 Chapter 934 Graphics Supplement, cont. class FileOrganizer, cont.

35 Chapter 935 Graphics Supplement, cont. class FileOrganizer, cont.

36 Chapter 936 Graphics Supplement, cont.


Download ppt "Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105."

Similar presentations


Ads by Google