1 /* 2 * File: ReadConnection.java 3 * 4 * Read a file on the server using the URLConnection class 5 * 6 * Copyright: Northeast Parallel Architectures Center 7 * 8 */ 9 10 import java.applet.Applet; 11 import java.awt.*; 12 import java.net.URL; 13 import java.net.URLConnection; 14 import java.net.MalformedURLException; 15 import java.io.InputStreamReader; 16 import java.io.BufferedReader; 17 import java.io.IOException; 18 19 public class ReadConnection extends Applet implements Runnable { 20 21 URL url; 22 Thread thread; 23 TextArea textarea = new TextArea( "Read Text..." ); 24 25 public void init() { 26 try { 27 url = new URL( getCodeBase(), "ReadConnection.java" ); 28 } catch ( MalformedURLException e ) { 29 System.err.println( "Bad URL: " + url.toString() ); 30 } 31 setLayout( new BorderLayout() ); 32 textarea.setFont( new Font( "Monospaced", Font.BOLD, 14 ) ); 33 add( textarea, BorderLayout.CENTER ); 34 } 35 36 public void start() { 37 if ( thread == null ) { 38 thread = new Thread( this ); 39 thread.start(); 40 } 41 } 42 43 public void stop() { 44 if ( thread != null ) { 45 thread.stop(); 46 thread = null; 47 } 48 } 49 50 public void run() { 51 String line; 52 StringBuffer buf = new StringBuffer(); 53 try { 54 URLConnection conn = url.openConnection(); 55 textarea.setText( "Opening connection..." ); 56 conn.connect(); 57 58 BufferedReader data = 59 new BufferedReader( 60 new InputStreamReader( conn.getInputStream() ) ); 61 62 textarea.setText( "Reading data..." ); 63 while ( ( line = data.readLine() ) != null ) { 64 buf.append( line + "\n" ); 65 } 66 data.close(); 67 68 textarea.setText( buf.toString() ); 69 } catch ( IOException e ) { 70 71 textarea.setText( "ReadConnection failed!" ); 72 System.err.println( "I/O Error:" + e.getMessage() ); 73 74 } 75 } 76 77 } // end ReadConnection class 78 79 80