streams and file i/o - purdue universitycs180/spring2007web/lecture... · 2005. 10. 20. · chapter...

80
Chapter 9 1 Streams and File I/O Chapter 9

Upload: others

Post on 24-Feb-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 1

Streams and File I/O

Chapter 9

Page 2: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 6

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.

Page 3: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 7

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.

Page 4: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 8

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.

Page 5: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 9

The Concept of a Stream, cont.

• This chapter discusses streams that connect programs to files.

Page 6: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 10

Why Use Files for I/O?

• Keyboard input and screen output deal only with temporary data, which is lost when the program ends.

• Files permit data to be stored permanently (or at least until a program changes the file).

• Input files can be used over and over by different programs.

• Files also provide convenient storage and retrieval of large quantities of data.

Page 7: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 11

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.

Page 8: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 12

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.

Page 9: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 14

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.

Page 10: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 15

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.

Page 11: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 17

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.

Page 12: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 18

Text-File Output with PrintWriter, cont.

• class TextFileOutputDemo

Page 13: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 21

Text-File Output with PrintWriter, cont.

• A file is opened using something similar tooutputStream = 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 are lost.– If the named file does not exist, a new

empty file is created (and named out.txt, for example).

Page 14: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 22

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.

• SyntaxPrintWriter Output_Stream_Name = new

PrintWriter (new FileOutputStream(File_Name));

Page 15: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 23

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.

Page 16: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 24

Some Methods in Class PrintWriter

• constructorPrintWriter(OutputStream streamObject)

• to create a new filenew PrintWriter(new

FileOutputStream(File_Name))

• to append new text to an old filenew PrintWriter(new

FileOutputStream(File_Name, true))

Page 17: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 25

Some Methods in Class PrintWriter, cont.

• to output to the file connected to the streampublic final void

println(Almost_Anything)public final void

print(Almost_Anything)

• To close a stream’s connection to a filepublic void close()

• To flush the output streampublic void flush()

Page 18: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 26

Closing Text Files

• When a program finishes writing to or reading from a file, it should close the file.– examplesoutputStream.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.

Page 19: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 27

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.

Page 20: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 29

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.

Page 21: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 30

Use toString for Text-File Output, cont.

• class Species

Page 22: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 31

Use toString for Text-File Output, cont.

• class TextFileObjectOutputDemo

Page 23: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 33

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 BufferedReaderaccepts a Reader object as an argument.

Page 24: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 34

Text-file Input with BufferedReader, cont.

• syntaxBufferedReader Stream_Name = new

BufferedReader(newFileReader(File_Name));

• Methods readln and read are used to read from the file.

• The FileReader constructor, and thus theBufferedReader constructor invocation can throw a FileNotFoundException.

Page 25: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 35

Text-file Input with BufferedReader, cont.

• class TextFileInputDemo

Page 26: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 38

Some Methods in Class BufferedReader

• constructorBufferedReader(Reader, readerObject)

• to create a streamnew BufferedReader(new

FileReader(File_Name))

• to read a line of input from the filepublic String readLine() throws IOException

– If the read operation goes beyond the end of the file, null is returned.

Page 27: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 39

Some Methods in Class BufferedReader, cont.

• to read a single character from the file and return it as an int valuepublic int read() throws IOException

– If the read operation goes beyond the end of the file, -1 is returned.

• to read a single character from the file and to treat it as a characterchar next = (char)(inputStream.read());

Page 28: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 40

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 filepublic void close()

Page 29: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 45

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.

Page 30: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 46

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.

Page 31: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 49

The StringTokenizerClass

• 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.utilpackage.

• Individual words are called tokens.

Page 32: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 50

The StringTokenizerClass, cont.

• Tokens are nonwhitespace characters.• example

StringTokenizer tokenizer = new StringTokenizer(“Read my lips!”)

while (tokenizer.hasMoreTokens()){

System.out.println(tokenizer.nextToken());

}

Page 33: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 51

The StringTokenizerClass, cont.

• This will produceReadmylips!

Page 34: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 52

The StringTokenizerClass, 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.,!”);

Page 35: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 53

Some Methods in Class StringTokenizer

• constructorspublic StringTokenizer(String

theString)public StringTokenizer(String

theString, String delimiters)

• more tokens?public boolean hasMoreTokens()

• next tokenpublic String nextToken()

Page 36: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 54

Some Methods in Class StringTokenizer, cont.

• remaining tokenspublic int countTokens()

Page 37: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 55

Java Tip: Testing for the End of a Text File

• When method readLine in class BufferedReaderattempts 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.

Page 38: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 56

Java Tip: Testing for the End of a Text File

• class EOFDemo

Page 39: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 57

The Classes FileReaderand FileOutputStream

• Class FileReader is used with class BufferedReader; class FileOutputStream is used with class Printwriter.

• Class FileReader and class FileOutputStreamaccept a file name as a constructor argument.

Page 40: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 58

The Classes FileReaderand 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.

Page 41: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 59

The Classes FileReaderand FileOutputStream,

cont.

• exampleBufferedReader inputStream =

new BufferedReader(new FileReader(“story.txt”);

Page 42: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 60

The Classes FileReaderand 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.

Page 43: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 61

The Classes FileReaderand FileOutputStream,

cont.

• examplePrintWriter OutputStream =

new PrintWriter(new FileOutputStream

(“stuff.txt”);

Page 44: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 62

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.

Page 45: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 63

Using the File Class, cont.

• The File class is like a wrapper class for strings which are file names.– examplenew File(“treasure.txt”)

Page 46: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 64

class FileClassDemo

Using the File Class, cont.

Page 47: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 65

Using the File Class, cont.

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

Page 48: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 66

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()

Page 49: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 68

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.

Page 50: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 69

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.

Page 51: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 70

Opening a Binary File

• syntaxObjectOutputStream Output_Stream_Name =

new ObjectOutputStream(new FileOutputStream(File_Name));

• exampleObjectOutputStream myOutputStream =

new ObjectOutputStream(new FileOutputStream

(“myfile.dat”));

Page 52: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 71

Output to Binary Files Using ObjectOutputStream

• class BinaryOutputDemo

Page 53: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 72

Output to Binary Files Using ObjectOutputStream,

cont.• The numbers are not in human-readable form

because there are no lines or other separators.

Page 54: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 73

Some Methods in Class ObjectOutputStream

• to createpublic ObjectOutputStream(OutputStream

streamObject)

• to create a streamnew ObjectOutputStream

(new FileOutputStream(File_Name_or_File_Object))

• to write a primitive typepublic void writeInt(int n) throws

IOException

Page 55: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 74

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

Page 56: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 75

Some Methods in Class ObjectOutputStream,

cont.public void writeChar(int n)

throws IOExceptionpublic void writeBoolean(boolean b)

throws IOException

• to write a Stringpublic void writeUTF(String aString)

throws IOException

Page 57: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 76

Some Methods in Class ObjectOutputStream,

cont.• To write an object

public void writeObject(ObjectanObject) throws IOException, NotSerializableException, InvalidClassException

• to closepublic void close() throws IOException

Page 58: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 77

Some Methods in Class ObjectOutputStream,

cont.• to flush

public void flush() throws IOException

Page 59: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 78

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.

Page 60: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 79

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.

Page 61: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 81

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

Page 62: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 83

Some Methods in Class ObjectInputStream

• to createObjectInputStream

(InputStream streamObject)

• to create a streamnew ObjectInputStream (new

FileInputStream

(File_Name_or_File_Object)

• to read a primitive typepublic int readInt() throws IOException

Page 63: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 84

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 IOExceptionpublic char readChar()

throws IOExceptionpublic boolean ReadBoolean()

throws IOException

Page 64: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 85

Some Methods in Class ObjectInputStream, cont.• to read a String

public String readUTF() throws IOException

• to read an objectpublic Object readObject()

throws ClassNotFoundException, InvalidClassException, OptionalDataException, IOException

• to closepublic void close() throws IOException

Page 65: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 86

Opening an Input File

• syntaxObjectInputStream Input_Stream_Name =

new ObjectInputStream(new

FileInputStream(File_Name));

• exampleObjectInputStream myInputStream = new

ObjectInputStream(new

FileInputStream(“myfile.dat”));

Page 66: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 89

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.

Page 67: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 90

• class EOFExceptionDemo

The EOFException Class

Page 68: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 92

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.

Page 69: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 93

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.

Page 70: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 94

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.

Page 71: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 101

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

• However, the class being written and read must be serializable.

Page 72: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 102

Binary I/O of Class Objects, cont.

• To make a class serializable, add implements Serializable to the class heading.

• examplepublic class SomeClass implements

Serializable

• The Serializable interface is available after importing java.io.*

Page 73: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 103

Binary I/O of Class Objects, cont.

• class Species

Page 74: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 104

Binary I/O of Class Objects, cont.

• class IODemo

Page 75: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 106

Files and toString

• Method toString provides convenient output to the screen and to a text file.

• However, method toString is not needed for object I/O to a binary file.

Page 76: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 107

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.

Page 77: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 114

Graphics Supplement• class FileOrganizer

Page 78: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 115

Graphics Supplement, cont.• class FileOrganizer, cont.

Page 79: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 116

Graphics Supplement, cont.• class FileOrganizer, cont.

Page 80: Streams and File I/O - Purdue Universitycs180/Spring2007Web/lecture... · 2005. 10. 20. · Chapter 9 6 The Concept of a Stream • Files can be used to store – Java classes –

Chapter 9 117

Graphics Supplement, cont.