I/O and Networking


Input and Output

Our applications and applet are rather useless if they can't read from or write to files. Therefore we need to know the basics of I/O, whether the file resides locally or on another server.

The following piece of code reads a file and dumps the contents to standard output because we use System.out.println(). We could have written the contents to another file by opening another stream.

import java.io.*;
public class DumpFile 
{	
	// character(non-GUI) application
	public static void main(String args[]) 
	{
		FileInputStream in = null;
		String	line;

		// We need wrap this sensitive area of code with
		// try/catch block to catch any exceptions that
		// have occurred
		try 
		{
	    		in = new FileInputStream(args[0]);
		} 
		catch (Throwable e) 
		{
	    		System.out.println("Usage: java DumpFile file");
	    		System.exit(1);
		}

		DataInputStream dis = new DataInputStream(in);

		// End-of-File is -1, but in this case as long as the
		// string returned is not null, continue
		try 
		{
			while ((line = dis.readLine()) != null) 
	    			System.out.println(line);
			in.close();
		}
		catch(IOException e)
		{
			System.out.println("I/O Error");
			System.exit(1);
		}
	}
}

Outputting data to a file. Prints Hello World to a file specified by the second parameter. Very foolish and only useful as an example.
import java.io.*;

public class OutputFile
{
	public static void main(String args[]) 
	{
		FileOutputStream out = null;

		// Attempt to open the file, if we can't display error
		// and quit
		try 
		{
	    		out = new FileOutputStream(args[1]);
		} 
		catch (Throwable e) 
		{
			System.out.println("Error in opening file");
	    		System.exit(1);
		}

		PrintStream ps = new PrintStream(out);
		
		try 
		{
			ps.println("Hello World");
			out.close();
		}
		catch(IOException e)
		{
			System.out.println("I/O Error");
			System.exit(1);
		}
    }
}
A basic CGI. The server must be either Solaris, Win95 or WinNT. Another common method is to read a HTML file and dump the contents to the standard output like DumpFile does. But this demostrates the concept of how CGIs work. Please read NCSA documentation on CGIs to learn more.
import java.io.*;

public class BasicCGI
{
        public static void main(String args[])
        {
		// HTML files need this header
		System.out.println("Content-type: text/html");
		System.out.println();

		// Now you could read in a file and dump the contents
		System.out.println("<HTML><HEAD>");
		System.out.println("<TITLE>Hello World</TITLE>");
		System.out.println("</HEAD>");
	
		// Body goes here
		
		System.out.println("</HTML>");
 	}
}

[Q & A's]

Q:Can applets use I/O?
A:Yes and No. Applets are restricted to I/O to and from the server. The only way to allow the applet to write to the client's side disk is for the user(client) to install special .class himself and modify the access rights.

Q:Best way to implement I/O in Applications?
A:Use FileDialog to save/write to files in addtion to using File/Data/Buffered Input/Output Streams


Networking

Networking in Java is fairly seamless, you can not really tell if you are writing to a local file or a file in Guam with an OutputStream. That is after you've opened the connection.

First thing to do is to open a connection. Lets go over what you can do(applets can't just jump to any site in the world and read files off the server. Everything you can do by Netscape should be possible by an applet )

URLs

Uniform Resource Locators are used on the web as a string identifier for a resource, rather than IP address(i.e 129.128.5.233) and a directory. You also must specify a protocol such as ftp, http, nntp, news, file, etc.

This simple example displays a button and with a click you goto to the tutorial

// The AWT package, applet package and networking package
import java.awt.*;
import java.applet.*;
import java.net.*;

public class URLTest extends Applet
{
        URL u = null;
	
        // This applet may not work if used locally via file://
        public void init()
        {
                setLayout(new BorderLayout());
        }

	// Add a button that is centered when clicked goes to the
	// tutorial
        public void start()
        {
                add("Center", new Button("Go to Tutorial"));
        }

	// action is called when the button has been clicked
        public boolean action(Event evt, Object arg)
        {
                if("Go to Tutorial".equals(arg))
                {
  			// If there is an error in creating the URL, we will
			// set it to the default
                      	try
                        {
				u = getDocumentBase();
                                u = new URL("http://ugweb.cs.ualberta.ca/~nelson/java/AWT.Tutorial.html");
                        }
                        catch(MalformedURLException u)
                        {
				showStatus("Error");
                        }

			// Uses the browser to display the
			// new document
                        getAppletContext().showDocument(u);
                        return true;
                }
                return false;
        }
}


To view this applet you'll need a Java-enabled browser

Note: The JDK Beta-2 and later added showDocument(url, target), where target is string specifying how you want to display the URL. i.e such in a new browser window.

URLConnections

After getting the URL, you'll need to open the connection with the URLConnection class. The following is some sample code on how this actually works
URL u = null;
URLConnection uc = null;


try
{
	u = new URL("http://ugweb.cs.ualberta.ca/~nelson/java/AWT.Tutorial.html");
}
catch(MalformedURLException e)
{
	System.out.println("Error in given URL");
	return;
}

// Now that you have the URL, open the connection
try
{
	uc = u.openConnection();
}
catch(IOException e)
{
	System.out.println("Error in opening URLConnection");
	return;
}
After opening the connection, what do you do? You now can read and write using InputStream/OutputStream. Both similar to FileInputStream and FileOutputStream...
	InputStream is = uc.getInputStream();
	OutputStream os = uc.getOutputStream();

Sockets

Sockets under applets are used to post data to CGIs, to communicate with the server, etc Under applications they are used to communciate with servers. You implement ftp, http, news protocols with sockets and can even control other applications with them.
// In general you do the following, where host is a machine
// name, i.e java.sun.com and port say is 80 if http
Socket socket = new Socket(host, port_number);
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
Under applets you must do the following.
Socket socket = new Socket(getDocumentBase().getHost(), getDocumentBase().getPort());
// Or
Because you still can not jump to an arbitrary site with applets and this includes sockets. Therefore examples such as "Stock ticker" are difficult without the use of a Server-side CGI and/or inter-applet communication.

Miscellaneous resources

[Q & A's]

Q: What else is there to know?
A: Quite a bit. You should read up on http://(the http protocol, URLs/URIs and TCP/IP(sockets).

Q:How do I do inter-applet communication, Is it useful?
A: Inter-applet communication can get around the one-site for each applet problem. Have one connect to the stock ticker server itself and pass the data to the other applet. Check out the FAQ by Elliotte Harold Russell.

Q: Do I really need to do the above?
A: No. But if want more than simple, connect and read/write a file from a server type applications, you will need to. (Note: HTTP may not allow you to write to a file on the server, whereas another protocol will)


[Next] [Prev] [Home]
Nelson Yu
nelson@cs.ualberta.ca
Last modified: Feb 21 1996