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.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

CS Network Programming CS 3331 Fall CS 3331 Outline Socket programming Remote method invocation (RMI)
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Prepared By E. Musa Alyaman1 URLs, InetAddresses, and URLConnections Chapter 9.
XP Browser and Basics1. XP Browser and Basics2 Learn about Web browser software and Web pages The Web is a collection of files that reside.
Remote Method Invocation Chin-Chih Chang. Java Remote Object Invocation In Java, the object is serialized before being passed as a parameter to an RMI.
1 L52 Networking (1). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Programming Applets How do Applets work ? This is an HTML page This is the applet’s code It has a link to an applet.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L24 (Chapter 25) Networking.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
15-Jul-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
COMPUTER TERMS PART 1. COOKIE A cookie is a small amount of data generated by a website and saved by your web browser. Its purpose is to remember information.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
Io package as Java’s basic I/O system continue’d.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
INTRODUCTION TO WEB DATABASE PROGRAMMING
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Web Security Programming I Building Security in from the Start Except where otherwise noted all portions of this work are Copyright (c) 2007 Google and.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
XP New Perspectives on Browser and Basics Tutorial 1 1 Browser and Basics Tutorial 1.
Dynamic Arrays Dynamic arrays are arrays that are re- allocated to a larger size. –See Eck Section 8.3 for details. –For instance, what happens with the.
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
Applets Chapter 17.  Java’s big splash onto the scene came in the mid 90’s. The people at Sun Microsystems had managed to work java programs into Web.
Java Server Pages A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format,
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
HOW WEB SERVER WORKS? By- PUSHPENDU MONDAL RAJAT CHAUHAN RAHUL YADAV RANJIT MEENA RAHUL TYAGI.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
Chapter 18 Networking F Client/Server Communications F Simple Client/Server Applications F Serve Multiple Clients F Create Applet Clients F Send and Retrieve.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Chapter 8 Introduction to HTML and Applets Fundamentals of Java.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
Application Layer Khondaker Abdullah-Al-Mamun Lecturer, CSE Instructor, CNAP AUST.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 25 – Ticket Information Application Introducing.
Chapter 16: Networking F Client/Server Communications F Serving Multiple Clients F Applet Clients F Viewing HTML Pages F Retrieving Files from Web Servers.
XP Tutorial 8 Adding Interactivity with ActionScript.
Field Trip #25 Creating a Client/Server By Keith Lynn.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
1 WWW. 2 World Wide Web Major application protocol used on the Internet Simple interface Two concepts –Point –Click.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Files and console applications Chapter 17 This chapter explains: What a file is How to read and write to files How to manipulate folder paths and file.
Basic ActionScript and PHP Cis 126. Getting Started set up a basic folder structure so we can keep our files organized. Mirror this structure on your.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit9: Internet programming 1.
java.io supports console and file I/O
Chapter 18 Networking Client/Server Communications
I/O Basics.
Clients and Servers 19-Nov-18.
Clients and Servers 1-Dec-18.
Uniform Resource Locator: URL
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Presentation 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""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 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 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.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 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: <!–– This is an automatically generated file. It will be read and overwritten. Do Not Edit! ––> Bookmarks Google Today’s new Check the weather

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 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 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 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 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 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 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 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 –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 pages parts of a URL –prefix “ –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 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 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 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

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 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 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 A portion of the HTML that would be displayed Current Weather Station Data (As of 02/15/04 9:22a) Temperature