CA597 Tutorial - Reading Remote Files


Content:
We will implement a program (NOT an applet for a change) which reads a file from a remote server and displays it on the screen - within a frame. A URL connection shall be used to transfer data.

The File

Here is the content of the file which shall be read:
abc     4
def     5
ghi     6
jkl     7
mno     8
pqr     9
stu     0
vwx     1
yz      2
Its location is the following URL
	http://www.compapp.dcu.ie/~cpahl/teach/ca597/in.dat
In the program, we are going to use this as a string parameter when we create a URL object
	URL url = new URL("http://sunsite.compapp.dcu.ie/~cpahl/teach/ca597/in.dat");

Handling Streams

In order to handle incoming file data, we need to access methods from the java.io package.
	import java.awt.*;
	import java.net.*;
	import java.io.*;
The stream we are using here is a buffered reader. Its advantages are that is deals with characters (so no conversion necessary, if we want to print it out), and it offers to read lines (instead of single characters or bytes).
	BufferedReader br = null;
Based on the string denoting the URL, we created a URL object. An input stream to the URL object shall then be opened. From this input stream we construct a buffered reader.
        InputStream is = url.openStream();
        br = new BufferedReader(new InputStreamReader(is));
These lines have to be embedded in an exception handling statement in order to deal with exceptions (caused by illegal URLs or IO problems) - see complete program below.

Output of File Content

The file content shall be displayed in a Frame object:
	public class FileContent extends Frame
Our class is based on the Frame class for this purpose. We use the frame instead of the browser window to display the content. A frame is similar to a panel, except that it is has a visible frame. But we can add other components to it.

We start with setting properties of the TextArea in which we want to display the file content.

	TextArea FileText =
                new TextArea("  Content of the File \'in.dat\' :",11,24,
     	                     TextArea.SCROLLBARS_NONE) ;
	...
	FileText.setBackground(Color.cyan);
        FileText.append(String.valueOf('\n'));
The textarea shall be added to the frame.
	Frame f = new Frame("File Content");
        f.setSize(200,200);
        f.add(FileText);
        f.setVisible(true);
The frame will be named "File Content". The last thing that remains to be done is to process the data from the buffered reader and display it on the screen. We read the file line by line until we reach the end of file (eof). In that case readLine() yields null. Then we close the connection.
	String s;
        boolean eof = false;
        s = br.readLine();
This defines a string s which shall contain a line of the file. eof is the end-of-file indicator. A first line is read into s from the buffered reader br.

As long as the end isn't reached we will write the current line of the file (temporarily stored in s) into our textfield (called FileText). Instead of overwriting the previous output, we need to append. The string s doesn't contain a 'newline', so we'll add one.

	FileText.append(s + String.valueOf('\n'));
As said above, when the end of the file is reached, readLine yields null and we can stop:
	s = br.readLine();
        if ( s == null )
        {
                  eof = true;
                  br.close();
        }
Again, we need to care for exceptions - see below.

The Code

Here is the full text of the program:

//
//	a program reading from a remote file
//	using a URL connection
//	Claus Pahl 
//	Feb 2000
//

import java.awt.*; 
import java.net.*; 
import java.io.*; 

public class FileContent extends Frame
{ 
	public static void main(String[] args) {

		BufferedReader br = null;
		TextArea FileText = 
		new TextArea("  Content of the File \'in.dat\' :",11,24,
			TextArea.SCROLLBARS_NONE) ; 

		try
		{	
			URL url = 
				new URL("http://sunsite.compapp.dcu.ie/~cpahl/teach/ca597/Material/in.dat");

                        InputStream is = url.openStream(); 
                        br = new BufferedReader(new InputStreamReader(is));
		}
		catch (MalformedURLException e)
		{
			System.out.println("Bad URL");
		}
		catch (IOException e)
		{
			System.out.println("IO Error : "+e.getMessage());
		}	

		FileText.setBackground(Color.cyan);
		FileText.append(String.valueOf('\n'));

		Frame f = new Frame("File Content");
		f.setSize(200,200);
		f.add(FileText); 
		f.setVisible(true);

		try
		{
			String s;
			boolean eof = false;
			s = br.readLine();

			while( !eof )
			{
				FileText.append(s + String.valueOf('\n'));
				try
				{
					s = br.readLine();
					if ( s == null )
					{
                        			eof = true;
						br.close();
					}
				}
				catch (EOFException eo)
                		{
                        		eof = true;
                		}
				catch (IOException e)
                		{
					System.out.println("IO Error : "+e.getMessage());
                		}
			}

		}
		catch (IOException e)
                {
                        System.out.println("IO Error : "+e.getMessage());
                }
	
	} 

}

How to Extend Your Program

What to do exactly?

© Claus Pahl