Streams and File I/O - PowerPoint PPT Presentation

About This Presentation
Title:

Streams and File I/O

Description:

Streams and File I/O Chapter 9 – PowerPoint PPT presentation

Number of Views:82
Avg rating:3.0/5.0
Slides: 81
Provided by: Rober1205
Category:

less

Transcript and Presenter's Notes

Title: Streams and File I/O


1
Streams and File I/O
  • Chapter 9

2
Objectives
  • become familiar with the concept of an I/O stream
  • understand the difference between binary files
    and text files
  • learn how to save data in a file
  • learn how to read data from a file

3
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
  • (optional) Graphics Supplement

4
Objectives, cont.
  • learn how use the classes ObjectOutputStream and
    ObjectInputStream to read and write class objects
    with binary files

5
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

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.

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.

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.

9
The Concept of a Stream, cont.
  • This chapter discusses streams that connect
    programs to files.

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.

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.

12
Text Files and Binary Files, cont.
  • Sometimes, it is more convenient to think of a
    files 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.

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

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.

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.

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

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.

18
Text-File Output with PrintWriter, cont.
  • class TextFileOutputDemo

19
Text-File Output with PrintWriter, cont.
20
Text-File Output with PrintWriter, cont.
  • File out.text now exists and contains
  • 1 A tall tree
  • 2 in a short forest is like
  • 3 a big fish in a small pond.

21
Text-File Output with PrintWriter, cont.
  • 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 are lost.
  • If the named file does not exist, a new empty
    file is created (and named out.txt, for example).

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.
  • Syntax
  • PrintWriter Output_Stream_Name new
  • PrintWriter (new
  • FileOutputStream(File_Name))

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.

24
Some Methods in Class PrintWriter
  • constructor
  • PrintWriter(OutputStream streamObject)
  • to create a new file
  • new PrintWriter(new
  • FileOutputStream(File_Name))
  • to append new text to an old file
  • new PrintWriter(new
  • FileOutputStream(File_Name, true))

25
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 streams connection to a file
  • public void close()
  • To flush the output stream
  • public void flush()

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

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.

28
Spelling File Names
  • The rules for spelling file names depend upon the
    operating system, not upon Java.
  • Operating systems typically allow you to use
    letters, digits, and the dot symbol to spell file
    names.
  • A suffix such as .txt indicates a text file, but
    that is just a common convention.

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.

30
Use toString for Text-File Output, cont.
  • class Species

31
Use toString for Text-File Output, cont.
  • class TextFileObjectOutputDemo

32
Use toString for Text-File Output, cont.
  • File species.records now exists and contains
  • Name Calif. Condor
  • Population 27
  • Growth rate 0.02
  • Name Calif. Condor
  • Population 27
  • Growth rate 0.02

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

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

35
Text-file Input with BufferedReader, cont.
  • class TextFileInputDemo

36
Text-file Input with BufferedReader, cont.
37
Text-file Input with BufferedReader, cont.
  • File data.txt existed previously and contained
  • 1 2
  • buckle my shoe.
  • 3 4
  • shut the door.

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

39
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 a single character from the file and to
    treat it as a character
  • char next (char)(inputStream.read())

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 streams connection to a file
  • public void close()

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

42
Programming Example Reading a File Name from the
Keyboard, cont.
  • class TextFileInputDemo2

43
Programming Example, cont.
44
Programming Example, cont.
  • File data.txt
  • 1 2
  • buckle my shoe.
  • 3 4
  • shut the door.

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.

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.

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

48
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)...

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

50
The StringTokenizer Class, cont.
  • Tokens are nonwhitespace characters.
  • example
  • StringTokenizer tokenizer new
  • StringTokenizer(Read my lips!)
  • while (tokenizer.hasMoreTokens())
  • System.out.println
  • (tokenizer.nextToken())

51
The StringTokenizer Class, cont.
  • This will produce
  • Read
  • my
  • lips!

52
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.,!)

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

54
Some Methods in Class StringTokenizer, cont.
  • remaining tokens
  • public int countTokens()

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

56
Java Tip Testing for the End of a Text File
  • class EOFDemo

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

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

59
The Classes FileReader and FileOutputStream, cont.
  • example
  • BufferedReader inputStream
  • new BufferedReader
  • (new FileReader(story.txt)

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

61
The Classes FileReader and FileOutputStream, cont.
  • example
  • PrintWriter OutputStream
  • new PrintWriter
  • (new FileOutputStream
  • (stuff.txt)

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.

63
Using the File Class, cont.
  • The File class is like a wrapper class for
    strings which are file names.
  • example
  • new File(treasure.txt)

64
Using the File Class, cont.
class FileClassDemo
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.

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

67
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

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.

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.

70
Opening a Binary File
  • syntax
  • ObjectOutputStream Output_Stream_Name
  • new ObjectOutputStream
  • (new FileOutputStream(File_Name))
  • example
  • ObjectOutputStream myOutputStream
  • new ObjectOutputStream
  • (new FileOutputStream
  • (myfile.dat))

71
Output to Binary Files Using ObjectOutputStream
  • class BinaryOutputDemo

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

73
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

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

75
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

76
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

77
Some Methods in Class ObjectOutputStream, cont.
  • to flush
  • public void flush() throws IOException

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.

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.

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

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 class ObjectOutputStream.

82
Reading Input from a Binary File Using
ObjectInputStream, cont.
83
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

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 IOException
  • public char readChar()
  • throws IOException
  • public boolean ReadBoolean()
  • throws IOException

85
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

86
Opening an Input File
  • syntax
  • ObjectInputStream Input_Stream_Name
  • new ObjectInputStream(new
  • FileInputStream(File_Name))
  • example
  • ObjectInputStream myInputStream new
  • ObjectInputStream(new
  • FileInputStream(myfile.dat))

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

88
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

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.

90
The EOFException Class
  • class EOFExceptionDemo

91
The EOFException Class, cont.
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.

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.

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.

95
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

96
The Classes FileInputStream and FileOutputStream,
cont.
  • example
  • ObjectOutputStream outputStream new
  • ObjectOutputStream(new
  • FileOutputStream(numbers.dat))

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

98
Programming Example Processing a File of Binary
Data, cont.
  • class Doubler

99
Programming Example Processing a File of Binary
Data, cont.
  • class Doubler, contd.

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

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 class
    ObjectInputStream.
  • However, the class being written and read must be
    serializable.

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

103
Binary I/O of Class Objects, cont.
  • class Species

104
Binary I/O of Class Objects, cont.
  • class IODemo

105
Binary I/O of Class Objects, cont.
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.

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.

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

109
Dont Mix Class Types
  • Its good programming practice to store data of
    only one class type on any one file.

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

111
Array Objects in Binary Files, cont.
  • class ArrayIODemo

112
Array Objects in Binary Files, cont.
113
(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).

114
Graphics Supplement
  • class FileOrganizer

115
Graphics Supplement, cont.
  • class FileOrganizer, cont.

116
Graphics Supplement, cont.
  • class FileOrganizer, cont.

117
Graphics Supplement, cont.
118
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.

119
Summary, cont.
  • You have learned how use the classes
    ObjectOutputStream and ObjectInputStream to read
    and write class objects with binary files.
Write a Comment
User Comments (0)
About PowerShow.com