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 paramter. 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:No. Applets are restricted to I/O to and from the server. The ony 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.

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.

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

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

[To be discussed]

[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: 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.


[Next] [Prev] [Home]
Nelson Yu
nelson@cs.ualberta.ca
Last modified: Dec 6 1995