import java.applet.*; import java.io.*; import java.net.*; import java.awt.*; //Applet that connects to a file on its server to read in //the first three lines and prints them out to the Java Console //Note: Applets can only perform FileIO with files on the // server on which the Applet resides. //Note: To access a file on the server from an Applet you need // to do the following steps: // 1)Create an instance of URL pointing to the url of the file // 2)Create an instance of URLConnection class by calling the // openConnection() method of your URL instance from step 1 // 3)Create an instance of InputStream class associated with your // URLConnection object of step 2 by calling its method getInputStream() public class myAppletIO extends java.applet.Applet { URL myURL; URLConnection myURLConnection; InputStream myIS; public void init() { String s; setBackground(Color.yellow); //Step 1&2: Create URL and URLConnection instances try{ myURL = new URL("http://www.mcs.csuhayward.edu/~grewe/CS3520/Mat/AppletIO/data.dat"); }catch(MalformedURLException e) {System.out.println("Can't access URL"); System.out.println("String: " + e.toString()); System.out.println("Message: " + e.getMessage()); } try{ myURLConnection = myURL.openConnection(); }catch(IOException e) {System.out.println("Can't open connection to URL"); } //Step 3: Get InputStream associated with URLConnection try { myIS = myURLConnection.getInputStream(); } catch(IOException e) {System.out.println("Can't access URL input"); } //NOW The rest is much like our examples in class to do // File Input //Now use myIS to read in contents of file and //print out to the Java Console //I have decided to use the BufferedReader class because //I like its readLine() method. Hence I need to convert //myIS (an Instance of InputStream) to a BufferedReader instance. //Step A: Convert myIS to an instance of InputStreamReader //Step B: Convert the instance of InputStreamReader to a // BufferedReader instance. //STEP A InputStreamReader myISR = new InputStreamReader(myIS); //STEP B BufferedReader BR = new BufferedReader(myISR); //Perform File Input with BufferedReader instance //Read the 3 input lines and write out to Java Console for(int i=0; i<3; i++) { try { s = BR.readLine(); System.out.println("Line " + i + ": " + s); }catch(IOException e) {System.out.println("can't read line " + i); } } //Close all streams try{ BR.close(); myISR.close(); myIS.close(); } catch(IOException e) {System.out.println("can't close streams"); } } }