import java.applet.*; import java.io.*; import java.net.*; import java.awt.*; //Applet that connects to a file on its server to write three //lines of text into the file. //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 OutputStream class associated with your // URLConnection object of step 2 by calling its method getOutputStream() public class myAppletOutput extends java.applet.Applet { URL myURL; URLConnection myURLConnection; OutputStream myOS; public void init() { String s; setBackground(Color.yellow); //Step 1&2: Create URL and URLConnection instances try{ myURL = new URL("ftp://www.mcs.csuhayward.edu/staff2/grewe/CS3520/Mat/dataOut.dat");//URL("http://www.mcs.csuhayward.edu/~grewe/CS3520/Mat/dataOut.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 OutputStream associated with URLConnection try { myOS = myURLConnection.getOutputStream(); } catch(IOException e) {System.out.println("Can't access URL outputstream"); System.out.println("String: " + e.toString()); System.out.println("Message: " + e.getMessage()); } //NOW The rest is much like our examples in class to do // File Input //Now use myOS to write out 3 lines of text to the file. //I have decided to use the BufferedWriter class because //I like its write() and newLine() methods. Hence I need to convert //myOS (an Instance of OutputStream) to a BufferedWriter instance. //Step A: Convert myOS to an instance of OutputStreamWriter //Step B: Convert the instance of OutputStreamWriter to a // BufferedWriter instance. //STEP A OutputStreamWriter myOSW = new OutputStreamWriter(myOS); //STEP B BufferedWriter BW = new BufferedWriter(myOSW); //Perform File Output with BufferedWriter instance //Write out 3 aribitrary lines to file try { s = "Hello class"; BW.write(s, 0, s.length()); BW.newLine(); s = "This is the 2nd line"; BW.write(s, 0, s.length()); s = "Goodbye...the last (3rd) line"; BW.write(s, 0, s.length()); BW.newLine(); }catch(IOException e) {System.out.println("can't write to file"); } //Close all streams try{ BW.close(); myOSW.close(); myOS.close(); } catch(IOException e) {System.out.println("can't close streams"); System.out.println("String: " + e.toString()); System.out.println("Message: " + e.getMessage()); } } }