Ch19 Streams, Files, Sockets, Exceptions

advertisement
Streams
• Files are a computer’s long term memory
• Need ability for programs to
– get information from files
– copy information from program variables to files
• Java streams provide connection between
variables internal to a program and external
files
1
More generally,
streams manage flows of data between
programs and any external entity that
can provide or receive data
ex. System.out
2
Stream Classes
• No class actually named Stream
• Collection of classes that provide
mechanism to transfer data between
programs and other external entities
• Distinction made between input and
output streams
• Distinction between streams that handle
text versus other forms of data
3
Text Streams
Many files contain only simple text
• Game programs remember high scores
in a text file
• Web browser keeps track of your
bookmarks in a text file
4
Bookmark Files
• Will consider manipulation of a
bookmarks file
• For each bookmark created, store pair
of strings
– web address (URL)
– description of the site at the address
• "Class to keep track of a single
bookmark"
5
Keeping Track of Bookmarks
Will need a class to keep track of a list of
bookmarks
• Assume class is named BookmarkList
• Assume methods
– add: adds a bookmark to end of list
– size: returns number of bookmarks in the list
– getSelectedItem: takes an int param and returns
bookmark at that position
6
Readers and Writers
• Readers: input streams specialized to
handle text
• Writers: output streams specialized to
handle text
Streams through which Java provides
access to text files called
– FileReader
– FileWriter
7
Creating a Writer
FileWriter bookmarksFile = new FileWriter( “bookmarks.html” );
– creates FileWriter stream to place data in file
named “bookmarks.html”
– file assumed to be in directory or folder current
when program is run
– if file does not already exist, new file created.
– if file exists, current contents erased to be
replaced by new data
8
Connections
• Constructing FileWriter establishes
connection between program and file
• program should explicitly destroy
connection when no longer needed
• terminate connection with close:
bookmarksFile.close();
9
Exceptions
• Operations involving streams can fail
• Many stream operations raise
exceptions that must be handled with a
try-catch
– all are subclasses of IOException class
10
Sending Data Through a
Writer
• FileWriter is a subclass of Writer
• all Writer classes include a write
method.
11
// Place all bookmark entries in bookmarks.html
public void saveBookmarksFile() {
try {
FileWriter bookmarksFile = new FileWriter( “bookmarks.html” );
for ( int i = 0; i < size(); i++ ) {
bookmarksFile.write( getSelectedItem(i).toString() );
}
bookmarksFile.close();
} catch ( IOException e ) {
System.out.println( “Unable to access bookmarks file - “
+ e.getMessage() );
}
}
12
Browser display of file produced by
saveBookmarksFile might look like:
13
Browser display of an actual bookmarks.html
14
Hypertext Markup Language
• text of real bookmarks file uses HTML:
<!DOCTYPE NETSCAPE-Bookmark-file-1>
<!–– This is an automatically generated file.
It will be read and overwritten.
Do Not Edit! ––>
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>
<DL><p>
<DT><A HREF=“http://www.google.com” >Google</A>
<DT><A HREF=“http://www.cnn.com” >Today’s new</A>
<DT><A HREF=“http://www.weather.com” >Check the weather</A>
</DL><p>
15
Change the line
bookmarksFile.write( getSelectedItem(i).toString() );
to
bookmarksFile.write( getSelectedItem(i).toBookmarkFileEntry() );
and invoke
// Return a string encoding the bookmark in the standard
// form browsers expect to find in bookmark files
public String toBookmarkFileEntry() {
return “<DT><A HREF=\”” + address + “\” >” + description + “</A>”;
}
• Still need preamble and epilogue
16
PrintWriters
• support println - convenient!
• constructor expects FileWriter as parameter
PrintWriter bookmarksFile =
new PrintWriter( new FileWriter( “bookmarks.html” ) ) ;
Revised saveBookmarksFile
17
Composing Writer Classes
Why construct a PrintWriter from a FileWriter?
• Deliberately designed division of labor
– FileWriter class handles details required to
access data in file
– PrintWriter provides programmer ability to send
data of various forms to a stream.
18
Readers
Organization of Reader classes parallels Writer classes
• all contain close method to terminate connection
• all contain a read method to transfer data from
Reader to a program variable
19
FileReader class
• subclass of Reader
• has constructor that takes String file name as
parameter
FileReader bookMarksReader = new FileReader( “bookmarks.html” );
• read method reads 1 character at a time
• constructor, close and read may raise IOExceptions;
need to handle with try-catch
20
BufferedReaders
• constructor accepts FileReader or any
other subclass of Reader
• supports method readLine
– each time invoked, next line from file is
read
– when no lines left, returns null
21
Most loops to process data from a BufferedReader take
the form:
String curLine = someBufferedReader.readLine();
while ( curLine != null ) {
// Code to process one line from the file
...
curLine = someBufferedReader.readLine();
}
retrieveBookmarksFile method
22
So Far
Readers and Writers
• Reader
– FileReader: allows read
– BufferedReader: allows readLine
• Writer
– FileWriter: allows write
– PrintWriter: allows println
23
Applets and Applications
Applets: Java programs designed to be
downloaded through a web browser
Applications: Designed to be installed locally.
For security of user’s files, web browsers
generally do not allow applets to access files
Programs that extend WindowController or
Controller designed to run as applets
24
Writing Applets and
Applications
• In every Java program, one class functions as
starting point of execution
• Applets
– class must be a subclass of Applet class or JApplet class
• Applications
– class must define a static method named main that expects
a string array as a parameter and returns no value.
public static void main( String arguments[ ] )
25
Writing an Application
• main method will be first thing executed
• typically one action of main will be to
create one or more objects of classes
that make up program
– common to construct object of the class in
which main defined
26
A Simple Application
Ex. A program that just creates a window
JustAWindow.java
27
Another Application
Ex. An application that allows user to get
current date and time
• Two components in window
– JTextArea
– JButton- user clicks to get date and time
28
The TimeClock Application
• Reuse ideas from JustAWindow
• Need event-handling method to display
date in response to clicks
• Initialization code
– will choose to put in a begin method
– call begin from main
TimeClock.java
29
The File System
• Your files organized into directories or
folders
• Directories or folders organized in
hierarchical structure
Programs need to know where to access files
30
Working with the File System
• File object
– encapsulates simple file name (like “bookmarks.html”)
and
– description of directory containing the file
– can be used in place of string parameter in FileReader and
FileWriter constructors
• JFileChooser
– enables Java to display dialog box; user chooses or creates
file through dialog box
– provides getSelectedFile method which returns File object
31
Using JFileChooser and File
Ex. A simple text editing application
– when program begins, assumes user
wants to open file to edit
– displays file contents in editable text area
– “Save” button that displays dialog box
through which user can save file.
– Text field used to display error messages
32
InstVars and begin method
33
Selecting a File for Reading
• use JFileChooser to select file
• create BufferedReader connected to selected file
Given instance variable
JFileChooser pickAFile = new JFileChooser();
// Use dialog box to let user select a file to open
private BufferedReader openInput() throws IOException {
int result = pickAFile.showOpenDialog( this );
if ( result == JFileChooser.APPROVE_OPTION ) {
return new BufferedReader(
new FileReader( pickAFile.getSelectedFile() ) );
} else {
return null;
}
}
Loading Text
34
How it Works
• showOpenDialog: requires a Component as a
parameter
– we pass it the program window
– thus dialog box will be placed above program
window
• showOpenDialog: returns an int
– whether user selected file or pressed cancel
• getSelectedFile: if file selected, returns a File
object
35
Selecting a File for Writing
• Very similar to selecting a file for
reading
• Differences
– use showSaveDialog rather than
showOpenDialog
– need to construct a way to write; we
construct a PrintWriter
Saving text
36
Network Communication
• Streams can be used to
– send data through computer networks
– receive data from computer networks
• Network communication almost always a twoway process
– to receive web page from remote server
• your browser sends request
• server sends requested page to your machine
• Streams for network communication almost
always come in pairs
– for sending data
– for receiving data
37
Sockets
• can be used to construct a pair of streams for
network communication as a single object
• two methods associated with each Socket object
– getInputStream
– getOutputStream
• use of streams associated with Socket nearly the
same as use of streams associated with files
– will use write to send messages
– readLine to receive messages
38
Clients and Servers
• Computers can act as clients and
servers
• Client: requests a service
– request to deliver an email
– request to let client view a web page
• Server: accepts requests and performs
desired services
39
Networking Protocols
• Rules that dictate types and formats of
messages that
– clients send to servers
– servers send to clients
• Ex. Hypertext Transfer Protocol (HTTP) :
rules that apply to web servers and clients
Will construct a simple web browser to
illustrate use of Socket
40
URLs
• addresses of web pages
http://nytimes.com/pages/national/index.html
• parts of a URL
– prefix “http://”
– name of server machine: “nytimes.com”
– path to a file stored on the server:
“/pages/national/index.html”
41
Port Numbers
• Depending on software running on a
machine, may act as
– a web server and
– a mail server and
...
• Port number specifies particular application
on a machine to which message should be
delivered
• Ex HTTP protocol specifies that messages for
port 80 go to web server application
42
Requesting a Web Page
• Create a Socket
Socket timesConnection = new Socket(“nytimes.com”,80);
– many ways construction can fail:
UnknownHostException, IOException
– need try-catch
• Create a stream to send data
OutputStream toTheTimesStream = timesConnection.getOutputStream();
43
Requesting a Web Page
(cont’d)
• Construct a stream specialized to process
type of data we want to send. For String data
Writer toTheTimes =
new OutputStreamWriter( timesConnection.getOutputStream() );
• Send a request
toTheTimes.write( “GET /pages/national/index.html” + “\n” );
Newline must be included- protocol says server responds
only after complete line received
44
Receiving Information
• Create a Socket
Socket server = new Socket(...);
• Create a stream to receive data
InputStream anInputStream = server.getInputStream();
• Construct a stream specialized to process type of
data we expect to receive
...new BufferedReader (new InputStreamReader
(anInputStream) );
• Read: with BufferedReader can use readLine()
45
A Socket Application
• Will write program to display raw HTML
for a weather web page
– get from http://climate.gi.alaska.edu/
46
High-Level Program Design
• Construct a Socket to establish
connection to server in Alaska
• Send a Request
• Display data returned
47
public void displayHTML() {
try {
Socket server = new Socket( “climate.gi.alaska.edu”, 80 );
sendRequest( server );
displayResponse( server );
server.close();
} catch ( IOException e ) {
System.out.println( “Connection failed - “
+ e.getMessage() ) ;
}
}
48
Sending the Request
private void sendRequest( Socket server ) throws IOException {
Writer toWebServer = new OutputStreamWriter( server.getOutputStream()
);
toWebServer.write( “GET /” + “\n” );
toWebServer.flush();
}
Note:
flush forces OutputStreamWriter to immediately send
data
49
Displaying the Response
private void displayResponse( Socket server ) throws IOException {
BufferedReader html = new BufferedReader(
new InputStreamReader( server.getInputStream())
);
String curLine = html.readLine();
while ( curLine != null ) {
System.out.println( curLine );
curLine = html.readLine();
}
}
50
A portion of the HTML that would be displayed
<TABLE BORDER=0 WIDTH=380 HEIGHT=77>
<TR>
<TD HEIGHT=17 BGCOLOR=“#FFFFFF”>
<CENTER><FONT SIZE=“-2” FACE=“Veranda”>Current Weather
Station Data (As of 02/15/04 9:22a)</FONT>
<P><TABLE BORDER=3 CELL PADDING=0 WIDTH=400 HEIGHT=36
align=center>
<TR>
<TD WIDTH=100 BGCOLOR=“#F0F8FF”>
<CENTER><FONT SIZE=“-2” FACE=“Veranda”>
<STRONG>Temperature</STRONG></FONT></CENTER>
</TD>
<TD WIDTH=“25%” BGCOLOR=“#F0F8FF”>
<CENTER><FONT SIZE=“-2” FACE=“Veranda”>
51
Download