1 streams files are a computer’s long term memory need ability for programs to –get information...

51
1 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

Upload: marjorie-roberts

Post on 02-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

1

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

2

More generally,

streams manage flows of data between programs and any external entity that can provide or receive data

ex. System.out

3

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

4

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

5

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"

6

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

7

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

8

Creating a WriterFileWriter 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

9

Connections

• Constructing FileWriter establishes connection between program and file

• program should explicitly destroy connection when no longer needed

• terminate connection with close:

bookmarksFile.close();

10

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

11

Sending Data Through a Writer

• FileWriter is a subclass of Writer• all Writer classes include a write

method.

12

// Place all bookmark entries in bookmarks.htmlpublic 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() );

}}

13

Browser display of file produced by saveBookmarksFile might look like:

14

Browser display of an actual bookmarks.html

15

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>

16

Change the linebookmarksFile.write( getSelectedItem(i).toString() );

tobookmarksFile.write( getSelectedItem(i).toBookmarkFileEntry() );

and invoke// Return a string encoding the bookmark in the standard// form browsers expect to find in bookmark filespublic String toBookmarkFileEntry() {

return “<DT><A HREF=\”” + address + “\” >” + description + “</A>”;

}

• Still need preamble and epilogue

17

PrintWriters

• support println - convenient!

• constructor expects FileWriter as parameter

PrintWriter bookmarksFile = new PrintWriter( new FileWriter( “bookmarks.html” ) ) ;

Revised saveBookmarksFile

18

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.

19

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

20

FileReader class

• subclass of Reader• has constructor that takes String file name as

parameterFileReader 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

21

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

22

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

23

So Far

Readers and Writers

• Reader– FileReader: allows read– BufferedReader: allows readLine

• Writer– FileWriter: allows write– PrintWriter: allows println

24

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

25

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[ ] )

26

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

27

A Simple Application

Ex. A program that just creates a window

JustAWindow.java

28

Another ApplicationEx. An application that allows user to get

current date and time• Two components in window

– JTextArea– JButton- user clicks to get date and time

29

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

30

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

31

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

32

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

33

InstVars and begin method

34

Selecting a File for Reading• use JFileChooser to select file• create BufferedReader connected to selected fileGiven instance variable

JFileChooser pickAFile = new JFileChooser();// Use dialog box to let user select a file to openprivate 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

35

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

36

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

37

Network Communication• Streams can be used to

– send data through computer networks– receive data from computer networks

• Network communication almost always a two-way 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

38

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

39

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

40

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

41

URLs

• addresses of web pageshttp://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”

42

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

43

Requesting a Web Page

• Create a SocketSocket timesConnection = new Socket(“nytimes.com”,80);

– many ways construction can fail: UnknownHostException, IOException

– need try-catch

• Create a stream to send dataOutputStream toTheTimesStream =

timesConnection.getOutputStream();

44

• Construct a stream specialized to process type of data we want to send. For String dataWriter toTheTimes =

new OutputStreamWriter( timesConnection.getOutputStream() );

• Send a requesttoTheTimes.write( “GET /pages/national/index.html” + “\n” );

Newline must be included- protocol says server responds only after complete line received

Requesting a Web Page (cont’d)

45

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

46

A Socket Application

• Will write program to display raw HTML for a weather web page– get from http://climate.gi.alaska.edu/

47

High-Level Program Design

• Construct a Socket to establish connection to server in Alaska

• Send a Request

• Display data returned

48

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

}

49

Sending the Requestprivate 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

50

Displaying the Responseprivate 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();

}}

51

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”>