Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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 2 More generally, streams manage flows of data between programs and any external entity that can provide or receive data ex. System.out

3 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 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 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""Class to keep track of a single bookmark"

6 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 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 8 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

9 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 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 11 Sending Data Through a Writer FileWriter is a subclass of Writer all Writer classes include a write method.

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

13 13 Browser display of file produced by saveBookmarksFile might look like:

14 14 Browser display of an actual bookmarks.html

15 15 Hypertext Markup Language text of real bookmarks file uses HTML: <!–– This is an automatically generated file. It will be read and overwritten. Do Not Edit! ––> Bookmarks Google Today’s new Check the weather

16 16 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 “ ” + description + “ ”; } Still need preamble and epilogue

17 17 PrintWriters support println - convenient! constructor expects FileWriter as parameter PrintWriter bookmarksFile = new PrintWriter( new FileWriter( “bookmarks.html” ) ) ; Revised saveBookmarksFile

18 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 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 20 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

21 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 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 23 So Far Readers and Writers Reader –FileReader: allows read –BufferedReader: allows readLine Writer –FileWriter: allows write –PrintWriter: allows println

24 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 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 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 27 A Simple Application Ex. A program that just creates a window JustAWindow.java

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

29 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 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 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 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 33 InstVars and begin method

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

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

42 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 43 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();

44 44 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 Requesting a Web Page (cont’d)

45 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 46 A Socket Application Will write program to display raw HTML for a weather web page –get from http://climate.gi.alaska.edu/

47 47 High-Level Program Design Construct a Socket to establish connection to server in Alaska Send a Request Display data returned

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

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

51 51 A portion of the HTML that would be displayed Current Weather Station Data (As of 02/15/04 9:22a) Temperature


Download ppt "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."

Similar presentations


Ads by Google