CS2 - PowerPoint PPT Presentation

1 / 29
About This Presentation
Title:

CS2

Description:

This is the world of your computer program. This is the outside world. Keyboard. Disk ... Now that the device (file or keyboard) is ready to provide input we ... – PowerPoint PPT presentation

Number of Views:87
Avg rating:3.0/5.0
Slides: 30
Provided by: ccGa
Category:

less

Transcript and Presenter's Notes

Title: CS2


1
CS2
  • Module 31
  • Category Elements of Java
  • Topic Input/Output
  • Objectives
  • Basic I/O
  • Streams

2
CS 2
  • Introduction to
  • Object Oriented Programming
  • Module 31
  • Elements of Java
  • Input Output

3
Printing to Screen
  • CS1
  • (display ltargumentgt)
  • Java
  • System.out.println(ltargumentgt)
  • System.out.println( ) // prints blank line
  • System.out.println(5) // prints 5
  • System.out.println("Hello World") // prints
    Hello World
  • "println" vs. "print" in Java
  • println includes "carriage return" at end, next
    print or println on new line
  • print causes next print or println to begin at
    next location on same line

Quick Review
4
Printing to Screen
  • String concatenation in Java is accomplished
    using ""
  • Use of "" will often appear in print and println
    parameter lists.
  • System.out.println("Average is " avgScore)
  • System.out.print("This is another handy "
  • "use of the concatenation operator "
  • "when the line is just too long, "
  • "you can break "
  • "it up this way")

Quick Review
5
Printing to Screen
  • Recall that Java has two predefined output
    streams.
  • System.out
  • System.err
  • In this course
  • use System.out
  • avoid System.err.
  • System.err is used by the autograders.

Quick Review
6
Java I/O Fun with Streams
  • In general, there are streams inherent in any
    Java process
  • System.in
  • System.out
  • System.err
  • You are already familiar with most of these
    streams. E.g.,
  • System.out.println(This is the output stream)
  • System.err.println(Something went wrong!)

7
Java I/O
  • Today well see how we can do several types of
    reading
  • read from standard input (the keyboard)
  • open a file and read from it.
  • even open a web URL and read from it!!!
  • Amazingly all three of these can be accomplished
    with a class called java.io.BufferedReader

8
Java I/O
  • Well also see how to write output
  • How to output to the screen
  • weve been using System.out.print
  • How to output to a file using a class called
    java.io.BufferedWriter

9
But First
This is the outside world
This is the world of your computer program
10
But First
Disk File
Disk File
This is the outside world
This is the world of your computer program
Keyboard
WWW
11
But First
Disk File
Disk File
This is the outside world
This is the world of your computer program
Keyboard
We need to make a connection between the two in
order to do input or output
WWW
Java has some (but not enough) already built in
12
Basics
  • A (possibly complicated) operation is performed
    to open some I/O device for input or output.
  • Attached to this operation is the establishment
    of some "simple" item that is used to refer to
    the file for subsequent I/O operations
  • In Java, an object is used (what a surprise) to
    handle the details so the "simple" item we use is
    a reference to the object
  • We typically open the device once and then
    perform numerous reads or writes
  • When done we close the device

13
Reading
  • Typically we will instantiate the class
    BufferReader, creating a BufferedReader object to
    suit our needs. (The complex part.)
  • BufferedReader to read from the
    keyboardBufferedReader keyboard new
    BufferedReader( new InputStreamReader(System.in)
    )
  • BufferedReader to read from a fileBufferedReader
    inFile new BufferedReader( new
    FileReader("foo.in"))
  • Well see reading from a URL later . . .

14
Typical methods
  • Now that the device (file or keyboard) is ready
    to provide input we can read one line at a time.
  • Where we are in the file is maintained for us
    automatically
  • When first opened, we are at the first line
  • Each readLine gets one line and positions us at
    the next line
  • NOTE DO NOT REOPEN THE FILE FOR EACH LINEopen
    once, read many times, close once.
  • Methods common for input(see class
    BufferedReader in the API for more info )
  • keyboard.readLine() inFile.readLine()
  • readLine returns a string. At the end of the file
    null is returned
  • Don't forget to close the file...
  • keyboard.close() inFile.close()

15
WritingHow to open a file for writing
  • PrintWriter outFile
  • new PrintWriter(
  • new BufferedWriter(
  • new FileWriter("foo.out")))
  • OR
  • PrintWriter outFile
  • outFile new PrintWriter(
  • new BufferedWriter(
  • new FileWriter("foo.out")))

What can go wrong? Check the API!!!
16
Opening a fileWhat can go wrong?
  • PrintWriter outFile
  • try
  • outFile new PrintWriter(
  • new BufferedWriter(
  • new FileWriter("foo.out")))
  • catch(FileNotFoundException e)
  • System.out.println("No such file silly
    rabbit!")
  • System.exit(0)

17
Typical methods
  • Now that the file is ready for output, we can
    write one line at a time.
  • Where we are in the file is maintained for us
    automatically
  • When first opened, we are at the top of the file
  • Each print or println writes one line (println
    also positions us at the next line
  • Methods common for output (see API for
    BufferedWriter, PrintWriter, FileWriter, etc.)
  • outFile.print(String s)
  • outFile.println(String s)
  • outFile.flush()
  • outFile.close()

18
Decorator Classes
  • Java IO uses decorator objects to provide
    layers of functionality to IO classes. Look at
    the following
  • InputStreamReader reader
  • new InputStreamReader(System.
    in)
  • BufferedReader console
  • new BufferedReader(reader)
  • OR
  • BufferedReader console
  • console new BufferedReader(
  • new InputStreamReader(System.in))
  • BufferedReader is called a Decorator Class.
  • BufferedReader adds the buffering capability

Pro/Con Flexibility with the cost of complexity
Sometimes called Wrapper classes (don't confuse
with...
19
Big Secret
  • Java I/O seems incredibly complex especially if
    you're a beginner
  • The original I/O system was thrown together
  • An improvement was made but all the old stuff is
    still there
  • Rumor has it that they're rewriting it
    (someday???)
  • To do a most of what you need, remember two
    classes
  • BufferedReader
  • BufferedWriter
  • They have examples of the basics we've
    demonstrated here.

20
Trivial example write a message to a File
import java.io. public class SillyWriteFile
private PrintWriter outFile public
static void main(String args) try
outFile new PrintWriter( new
FileWriter(silly.out))
outFile.println(This gets printed to file)
outFile.close() catch (IOException
e) System.out.println(problem with
file) // main // SillyWriteFile
21
Trivial example read and echo a file
import java.io. public class SillyEchoFile
private BufferedReader inFile public static
void main(String args) String line
try inFile new BufferedReader(
new FileReader(data.txt))
while((line inFile.readLine()) ! null)
System.out.println(line) // end while
inFile.close() // end try catch
(IOException e) System.out.println(proble
m with file) // end catch // main
// SillyEchoFile
LOOP
Make sure you "get" this magic while((line
inFile.readLine()) ! null)
22
Better example of file I/O
import java.io. public class TextIO
private String filename public void
echoFile() throws IOException
BufferedReader myFile new
BufferedReader(new FileReader(filename))
String line while ((line
myFile.readLine()) ! null)
System.out.println(line) // while
myFile.close() // echoFile
See next slide for this
23
Better example of file I/O
public void promptUserFilename() throws
IOException BufferedReader keyboard
new BufferedReader( new
InputStreamReader(System.in))
System.out.println(Please enter filename)
filename keyboard.readLine() //
promptUserFilename public String getFilename()
return filename // getFilename
24
Better example of file I/O
public static void main(String a) throws
IOException TextIO text1 new TextIO()
boolean success false while (!success)
try text1.promptUserFilename()
if (!text1.getFilename().equalsIgnoreCase(q
)) text1.echoFile() success
true // try catch
(FileNotFoundException e)
System.out.println(Hey, file cannot be
found.) System.out.print(Enter new
filename) System.out.println( or q
to quit.) // catch // notice that
if some other exception occurs, we // do
not catch it so main throws IOException
// while // main // TextIO
25
Success false
Get filename/Open file
IOE
FileNotFound Exception?
Error Message
true
false
true
filename"q"
Exit
false
echoFile
IOE
Success true
Success?
true
false
26
And reading a URL????
  • import java.net.
  • import java.io.
  • public class MyURLReader
  • public static void main(String a) throws
    Exception
  • String line
  • URL myURL new URL("http//www.cc.gatech.edu/
    ")
  • URLConnection uc myURL .openConnection()
  • BufferedReader in new BufferedReader
  • (new InputStreamReader(uc.getInputStream()))
  • while ((line in.readLine()) ! null)
  • System.out.println(line)
  • in.close()

27
BufferedReader strikes again!
  • What do you know, even a URL can be used to
    create our old familiar input device, the
    BufferedReader
  • Makes reading from a URL over the internet almost
    as trivial as reading from a file or the
    keyboard!
  • Having the same interface is very handy this is
    all thanks to the decorator class concept

28
Questions?
29
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com