File Input and Output - PowerPoint PPT Presentation

1 / 29
About This Presentation
Title:

File Input and Output

Description:

Another interesting note is that there are no methods in this class. Huh? ... The condition on the while loop is looking for end-of-file which is indicated by ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 30
Provided by: davemcp
Category:

less

Transcript and Presenter's Notes

Title: File Input and Output


1
File Input and Output
  • Not in the book

2
Introduction
  • Java doesnt exactly make input and output
    straight forward
  • They do make it extremely flexible and very
    powerful.
  • As it often happens, with power and flexibility
    comes complexity.
  • Java provides around 60 or so objects to handle
    input and output.

3
Basic File Input
  • The basic file input class is the FileReader
  • FileReader allows you to attach to a file and
    read it out a character at a time.
  • This class has several constructors
  • The most useful (for us right now) takes a String
    that is the file name
  • Another interesting note is that there are no
    methods in this class

4
Huh?
  • How is that possible?
  • All of the methods come from parent classes.
  • This is an example of Javas inheritance
    mechanism.

5
Inheritance Basics
  • Java allows you to create a class and define
    behavior that is to exist in a class.
  • Then you realize that another class needs to do
    something similar.
  • You dont have to recode all of those methods,
    you can inherit them.
  • After you declare the class you add the keyword
    extends and then the name of the class
  • This allows you to use the methods of the
    extended class without rewriting them

6
Back to FileReader
  • FileReader extends InputStreamReader which in
    turn extends Reader.
  • It is the read method of the InputStreamReader
    and Reader that we will use
  • The read method will allow us to read in one
    character at a time and process each character in
    turn.

7
Of course theres more
  • In addition of inheritance Java uses an error
    handling mechanism call exceptions.
  • When you create and use a a FileReader you have
    to know what exceptions could be thrown and take
    the appropriate actions.
  • Maybe an example would help.

8
RemoveNewlines
  • public RemoveNewlines( String inFile )
  • fileName inFile
  • try
  • input new FileReader( fileName )
  • catch ( FileNotFoundException e )
  • e.printStackTrace()

9
cleanFile
  • public void cleanFile( FileWriter out )
  • int ch -1
  • int carriageReturn 13
  • int newline (int)'\n'
  • try
  • ch input.read()
  • catch ( IOException e )
  • e.printStackTrace()
  • int nextChar 0
  • while ( ch ! -1 )

10
  • if ( ch carriageReturn )
  • try
  • nextChar input.read()
  • nextChar input.read()
  • catch ( IOException e )
  • e.printStackTrace()
  • ch -1
  • if ( nextChar ch )
  • try
  • input.read()
  • out.write( '\n' )
  • out.write( '\n' )
  • else
  • try
  • out.write( ' ' )
  • out.write( nextChar )
  • catch ( IOException e )
  • e.printStackTrace()
  • else
  • try
  • out.write( ch )

11
Last Bit
  • try
  • ch input.read()
  • catch ( IOException e )
  • e.printStackTrace()

12
Some things to notice
  • In the middle of all that goo, there is a pattern
    to notice.
  • There is a piece of data read
  • Then it was checked
  • Then it was processed
  • Another piece of data is read
  • And the process repeats

13
This is a good pattern to remember
  • This is known as a priming read.
  • When you read the first piece of data, you are
    trying to make sure that the file contains
    information.
  • The condition on the while loop is looking for
    end-of-file which is indicated by -1.

14
FileWriter
  • The FileWriter class is the basic class that
    allows us to write characters to a file in Java.
  • Just like the FileReader class, the FileWriter
    class only has constructors and it inherits all
    of its methods from its parent class,
    OutputStreamWriter.
  • The OutputStreamWriter then extends the Writer
    class.

15
Useful Methods
  • The FileWriter class has analogous methods to the
    FileReader
  • Where we used read before, now we use write
  • Both classes have a close method that closes the
    files and gives back the resources to the system.
  • If you forget to close the FileWriter object,
    then the data you are writing to the file may not
    be there.

16
Problem with FileReader
  • The biggest problem with the FileReader class is
    that it works with character data
  • This is fine if you are in first grade and are
    just learning the alphabet
  • Usually we need to deal with pieces of text that
    is greater than a single character

17
BufferedReader
  • Java has a class called the BufferedReader to do
    just this.
  • Finally, we have a reader class that introduces
    its own methods
  • The readLine method does just what it sounds
    like, it reads an entire line of a file and
    returns it in a string.

18
Creating a BufferedReader
  • A BufferedReader requires another reader at its
    construction.
  • This may seem a little weird, but it will use the
    methods of that reader to do its job.
  • You can use an anonymous class to do the trick
  • new BufferedReader( new FileReader( Goo.txt ) )

19
A little more detail
  • Of course that throws an exception that must be
    handled, so heres the entire construction
  • try
  • bf new BufferedReader( new FileReader(
    Goo.txt ) )
  • catch ( FileNotFoundException e)
  • e.printStackTrace()

20
Just to clarify
  • So that the last slide does not seem confusing,
    the creation of the BufferedReader does not throw
    a file not found exception, it is the creation of
    the FileReader that does.
  • If you used a different reader as the anonymous
    class then it could throw a different type of
    exception

21
How do you use one
  • Lets suppose you have a BufferedReader, bf, and
    you want to use it.
  • We will most often be using the readLine method.
  • It follows the general pattern like this
  • Read a line
  • While the line is not null
  • Process the line
  • Read a line

22
Example
  • try
  • line bf.readLine()
  • catch (IOException e)
  • e.printStackTrace()
  • while ( line ! null )
  • String words line.split()
  • //process words
  • try
  • line bf.readLine()
  • catch (IOException e)
  • e.printStackTrace()

23
readLine
  • The readLine method will be one that we use most
    often
  • It will return the next line from the stream or
    null if the end of the stream has been
    encountered
  • The question is what do we do with the string
    after we get it back.

24
Two Choices
  • The last example showed using a method of the
    String class called split.
  • Split will take a string a split it up based on
    what was given between the quotes.
  • Split will return an array of strings
  • You can then use the length of the array to walk
    through it and process the line

25
Second Choice
  • The alternative choice is a class called
    StringTokenizer
  • The StringTokenizer works in a similar manner as
    an iterator.
  • Once you have tokenized the string, you can ask
    if it has more tokens and get the next token.
  • import java.util.StringTokenizer

26
Example
  • String s input.readLine()
  • while ( s ! null )
  • StringTokenizer sT new StringTokenizer( s,
    )
  • while ( sT.hasMoreTokens() )
  • String otherS sT.nextToken()
  • s input.readLine()

27
What about writing to a file?
  • Just like we had issues with having to read a
    character at a time
  • Its fairly tedious to have to write a character
    at a time
  • Java of course has a solution
  • The PrintWriter class

28
Creating a PrintWriter
  • Just like the FileReader required another stream,
    so does the PrintWriter
  • Example
  • pW new PrintWriter( new FileWriter( Goo.txt )
    )
  • Of course dont forget that the FileWriter could
    throw an exception.

29
Using a PrintWriter
  • Using a PrintWriter is easy
  • Use the familiar print and println methods just
    like System.out
  • This makes it easier to use the methods
  • There is no really easy way to format output
    until you start using Java 5.0
Write a Comment
User Comments (0)
About PowerShow.com