Presentation is loading. Please wait.

Presentation is loading. Please wait.

Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.

Similar presentations


Presentation on theme: "Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object."— Presentation transcript:

1 Streams and File I/O Chapter 9

2 Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object Streams

3 Overview of Streams and File I/O: Outline The Concept of a Stream Why Use Files for I/O? Differences Between Text Files and Binary Files

4 The Concept of a Stream Files can be used to store –Java classes –Java programs –output from a program –input for a program. File I/O as well as keyboard and screen I/O are handled by streams.

5 The Concept of a Stream, cont. A stream is a flow of data (characters, numbers, etc.). Data flowing into a program is called an input stream. Data flowing out of a program is called an output stream.

6 The Concept of a Stream, cont. A stream is implemented as an object. –It delivers data to a destination such as a file or a stream or –it takes data from a source such as a file or the keyboard, and delivers it to a program. System.out is the only output stream we have used so far. Objects of class Scanner, used for keyboard input, are streams, too. This chapter discusses steams that connect programs to files.

7 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. 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 Text Files and Binary Files, cont. Text files usually appear to be the same on all computers. Binary files usually differ from machine to machine and from programming language to programming language. –Normally, the computer and programming language used to create the file must be used to read the file.

9 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. Though text files can be read and written using an editor, binary files must be read and written by a program.

10 Text-File I/O: Outline Text-File Output with PrintWriter Text-File Input with BufferedReader The StringTokenizer Class The Classes FileReader and FileOutputStream

11 Text-File Output with PrintWriter Class PrintWriter has a method println that behaves like System.out.println The java.io package contains the class PrintWriter and the other file I/O classes discussed in this chapter.

12 Text-File Output with PrintWriter, cont.

13

14 A file is opened using something similar to outputStream = new PrintWriter( new FileOutputStream(“out.txt”)); –An empty file is connected to a stream. –If the named file ( out.txt, for example) exists already, its old contents is lost. –If the named file does not exist, a new empty file is created (and named out.txt, for example).

15 Text-File Output with PrintWriter, cont. Class Printwriter has no constructor that takes a file name as an argument. So, we use class FileOutputStream to create a stream and can be used as an argument to a PrintWriter constructor. Syntax PrintWriter Output_Stream_Name = new PrintWriter (new FileOutputStream(File_Name));

16 Text-File Output with PrintWriter, cont. The FileOutputStream constructor, and thus the PrintWriter constructor invocation can throw a FileNotFoundException, which means that the file could not be created. The PrintWriter object is declared outside the try block. –If it were declared inside the try block, it would be local to the try block.

17 Some Methods in Class PrintWriter constructor PrintWriter(OutputStream streamObject) to create a stream new PrintWriter(new FileOutputStream(File_Name)) to append new text new PrintWriter(new FileOutputStream(File_Name, true))

18 Some Methods in Class PrintWriter, cont. to output to the file connected to the stream public final void println(Almost_Anything) public final void print(Almost_Anything) To close a stream’s connection to a file public void close() To flush the output stream public void flush()

19 Closing Text Files When a program finishes writing to or reading from a file, it should close the file. –examples outputStream.close(); inputStream.close(); If a program does not close a file before the program ends, Java will will close it when the program ends, provided the program ends normally.

20 Closing Text Files, cont. The sooner a file is closed, the less likely it is to be damaged by being left open when a program ends abnormally. If a program writes a file, it must close the file before it attempts to read from it.

21 Text-file Input with BufferedReader Class BufferedReader is the preferred stream class for reading from a text file. Class BufferedReader has no constructor that takes a filename as its argument. –Class FileReader accepts a file name as a constructor argument and produces a stream that is a Reader object. –The constructor for class BufferedReader accepts a Reader object as an argument.

22 Text-file Input with BufferedReader, cont. syntax BufferedReader Stream_Name = new BufferedReader(new FileReader(File_Name)); Methods readln and read are used to read from the file. The FileReader constructor, and thus the BufferedReader constructor invocation can throw a FileNotFoundException.

23 Text-file Input with BufferedReader, cont.

24 Some Methods in Class BufferedReader constructor BufferedReader(Reader, readerObject) to create a stream new BufferedReader(new FileReader(File_Name)) to read a line of input from the file public String readLine() throws IOException –If the read operation goes beyond the end of the file, null is returned.

25 Some Methods in Class BufferedReader, cont. to read a single character from the file and return it as an int value public int read() throws IOException –If the read operation goes beyond the end of the file, -1 is returned. to read read a single character from the file and to treat it as a character char next = (char)(inputStream.read());

26 Some Methods in Class BufferedReader, cont. To read a number from a text file, the number must be read in as a string and the string must be converted to a number. to close a stream’s connection to a file public void close()

27 Programming Example: Reading a File Name from the Keyboard A user may need to enter a file name at the keyboard at the time a program is run.

28 Programming Example: Reading a File Name from the Keyboard, cont.

29 Java Tip: Using Path Names When providing a file name as an argument for opening a file, a simple file name may be used if the file is in the same directory as the program being run. A full or relative path name also can be used. A full path name is the complete path name, starting from the root directory.

30 Java Tip: Using Path Names, cont. A relative path name is the path name starting from the directory containing the program. The way to specify path names depends upon the operating system.

31 Java Tip: Using Path Names, cont. example - UNIX /user/smith/home.work1/data.txt … new FileReader (“/user/smith/home.work1/data.txt”)… example - Windows D:\homework\hw1\data.txt … new FileReader (“D:\\homework\\hw1\\data.txt”)…

32 Java Tip: Using Path Names, cont. The \\ would be used if the path name is hardcoded, but the \ would be used if the path name is entered from the keyboard. A Java program will accept a path name written in either Windows or UNIX format, even if a computer is using an operating system that does not match the syntax....(“D:/homework/hw1/data.txt”)...

33 The 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.

34 The StringTokenizer Class, cont. Tokens are nonwhitespace characters. example StringTokenizer tokenizer = new StringTokenizer(“Read my lips!”) while (tokenizer.hasMoreTokens() { System.out.println (tokenizer(nextToken()); } This will produce Read my lips!

35 The StringTokenizer Class, cont. 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.,!”);

36 Some Methods in Class StringTokenizer constructors public StringTokenizer(String theString) public StringTokenizer(String theString, String delimiters) more tokens? public boolean hasMoreTokens() next token public String nextToken() remaining tokens public int countTokens()

37 Java Tip: Testing for the End of a Text File When method readLine in class BufferedReader attempts to read beyond the end of a file, the method returns the value null. When method read attempts to read beyond the end of a file, the method returns the value -1.

38 Java Tip: Testing for the End of a Text File

39 The Classes FileReader and FileOutputStream Class FileReader is used with class BufferedReader ; class FileOutputStream is used with class Printwriter. Class FileReader and class FileOutputStream accept a file name as a constructor argument.

40 The Classes FileReader and FileOutputStream, cont. Connecting a BufferedReader object to a file using a string name requires two steps. –First, create an object of the class FileReader. –Then use this object to create an object of class BufferedReader. example –BufferedReader inputStream = – new BufferedReader – (new FileReader(“story.txt”);

41 The Classes FileReader and FileOutputStream, cont. Producing a PrintWriter output stream from a file using FileOutputStream requires two steps. –First, create an object of the class FileOutputStream. –Then use this object to create an object of class PrintWriter.

42 The Classes FileReader and FileOutputStream, cont. example PrintWriter OutputStream = new PrintWriter (new FileOutputStream (“stuff.txt”);

43 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. The File class is like a wrapper class for strings which are file names. –example new File(“treasure.txt”)

44 Using the File Class, cont.

45 Method canWrite determines if the operating system will let you write to the file. Typically, the operating systems lets you designate files as not writeable or as writeable only by certain users.

46 Some Methods in the Class File public boolean exists() public boolean canRead() public boolean canWrite() public boolean delete() public boolean length() public String getName() public String getPath()

47 Basic Binary-File I/O: Outline Output to Binary Files Using ObjectOutputStream (optional) Some Details About writeUTF Reading Input from a Binary File Using ObjectInputStream The EOFException Class The Classes FileInputStream and FileOutputStream

48 Binary Files Binary files store data in the same format used for main memory. Bytes in main memory and bytes in binary files are read similarly, which leads to efficiency. Binary files created by a Java program on one computer can read by a Java program on a different computer.

49 Binary Files, cont. Class ObjectInputStream and class ObjectOutputStream are used to process binary files. –Data is read or written, one byte at a time. –Numbers and characters are converted automatically to bytes for storage in a binary file. –Data in files can be treated as Java primitive data types, as strings, or as other objects.

50 Opening a Binary File syntax ObjectOutputStream Output_Stream_Name = new ObjectOutputStream (new FileOutputStream(File_Name)); example ObjectOutputStream myOutputStream = new ObjectOutputStream (new FileOutputStream (“myfile.dat”));

51 Output to Binary Files Using ObjectOutputStream

52 Output to Binary Files Using ObjectOutputStream, cont. The numbers are not in human-readable form because there are no lines or other separators.

53 Some Methods in Class ObjectOutputStream to create public ObjectOutputStream(OutputStream streamObject) to create a stream new ObjectOutputStream (new FileOutputStream (File_Name_or_File_Object)) to write a primitive type public void writeInt(int n) throws IOException

54 Some Methods in Class ObjectOutputStream, cont. to write a primitive type, cont. public void writeLong(long n) throws IOException public void writeDouble(double x) throws IOException public void writeFloat(float x) throws IOException

55 Some Methods in Class ObjectOutputStream, cont. public void writeChar(int n) throws IOException public void writeBoolean(boolean b) throws IOException to write a String public void writeUTF(String aString) throws IOException

56 Some Methods in Class ObjectOutputStream, cont. To write an object public void writeObject(Object anObject) throws IOException, NotSerializableException, InvalidClassException to close public void close() throws IOException to flush public void flush() throws IOException

57 Some Methods in Class ObjectOutputStream, cont. There is no method writeString. Instead, use method writeUTF. UTF stands for Unicode Text Format. UTF provides short, efficient codes for ASCII characters.

58 Different Types in the Same File Different types can be written to the same file. However, the different types must be read from the file just as they were written to the file.

59 (optional) Some Details About writeUTF Method writeUTF uses different numbers of bytes to store strings of different lengths in a file. However, there are no separators between data items in a binary file. Java resolves this problem by writing extra information at the start of each string (i.e. the number of bytes used to write the string).

60 Reading Input from a Binary File Using ObjectInputStream A file written using ObjectOutputStream can be read using ObjectInputStream. The methods in class ObjectInputStream correspond to the methods in class ObjectOutputStream. class BinaryInputDemo

61 Some Methods in Class ObjectInputStream to create ObjectInputStream (InputStream streamObject) to create a stream new ObjectInputStream (new FileInputStream (File_Name_or_File_Object) to read a primitive type public int readInt() throws IOException

62 Some Methods in Class ObjectInputStream, cont. to read a primitive type, cont. public long readLong() throws IOException public double readDouble() throws IOException public float readFloat() throws IOException public char readChar() throws IOException public boolean ReadBoolean() throws IOException

63 Some Methods in Class ObjectInputStream, cont. to read a String public String readUTF() throws IOException to read an object public Object readObject() throws ClassNotFoundException, InvalidClassException, OptionalDataException, IOException to close public void close() throws IOException

64 Opening an Input File syntax ObjectInputStream Input_Stream_Name = new ObjectInputStream(new FileInputStream(File_Name)); example ObjectInputStream myInputStream = new ObjectInputStream(new FileInputStream(“myfile.dat”));

65 Reading Binary Files and Text Files Do not attempt to read a binary file as if it were a text file (using BufferedReader ) or a text file as it if were a binary file (using ObjectInputStream ). –For the buffering, BufferedInputStream can be used.

66 DataInputStream and DataOutputStream ObjectInputStream and ObjectOutputStream uses JAVA`s own file header for the object save & load. –However, they can`t handle general binary files. DataInputStream and DataOutputStream can handle general binary files. –However, they can`t save and load JAVA objects directly.

67 Defining a Method to Open a Stream public static ObjectOutputStream openFile() throws IOException { ObjectOutputStream tempStreamName; System.out.println(“Enter file name: “); Scanner keyboard = new Scanner(System.in); String fileName = keyboard.next(); tempStreamName = new ObjectOutputStream(new FileOutputStream(fileName)); return tempStreamName; }

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

69 The EOFException Class

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

71 The Classes FileInputStream and FileOutputStream We used stream class FileInputStream when we created a stream of class ObjectInputStream. We used stream class FileOutputStream when we created a stream of class ObjectOutputStream.

72 The Classes FileInputStream and FileOutputStream, cont. FileOutputStream and FileInputStream accept a file name as a constructor argument. Neither ObjectInputStream nor ObjectOutputStream accepts a file name as an argument.

73 The Classes FileInputStream and FileOutputStream, cont. You connect an ObjectInputStream to a file using a string name in two steps. –Create an object of class FileOutputStream –Use this object of class FileOutputStream to create an object of class ObjectOutputStream

74 The Classes FileInputStream and FileOutputStream, cont. example ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(“numbers.dat”));

75 Programming Example: Processing a File of Binary Data Ask the user for two file names. Read the numbers in one file, multiply each number by two, and write the results to other file.

76 Programming Example: Processing a File of Binary Data, cont.

77

78 Object I/O with Object Streams: Outline Binary I/O of Class Objects The Serializable Interface Array Objects in Binary Files

79 Binary I/O of Class Objects Using method writeObject of class ObjectOutputStream you can output class objects to a binary file, and then read objects from the file using method readObject of class ObjectInputStream. However, the class being written and read must be serializable.

80 Binary I/O of Class Objects, cont. To make a class serializable, add implements Serializable to the class heading. example public class SomeClass implements Serializable The Serializable interface is available after importing java.io.*

81 Binary I/O of Class Objects, cont.

82

83

84 The Serializable Interface A class which is serializable effects 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.

85 The Serializable Interface, cont. This makes file I/O more efficient and makes files smaller. When read with a stream of type ObjectInputStream, duplicate serial numbers are returned as references to the same object. When a serializable class has instance variables of a class type, the class for the instance variables should be serializable.

86 Don’t Mix Class Types It’s good programming practice to store data of only one class type on any one file.

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

88 Summary You have become familiar with the concept of an I/O stream. You now understand the difference between binary files and text files. You have learned how to save data in a file. You have learned how to read data from a file. You have learned how use the classes ObjectOutputStream and ObjectInputStream to read and write class objects with binary files.


Download ppt "Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object."

Similar presentations


Ads by Google