Often one of the first applets that new Java programmers want
to write for their own work involves reading a file of some sort.
This could be simple database information such as a list or table
of values and labels in text format.
We have learned to read image files and audio files
from an applet but have not yet read a text file. This is actually
fairly easy to do. However, keep in mind that for applets the
SecurityManager
(to be discussed in Chapter
14) restricts access to only those files accessible from the
location of the web page on which the applet code resides.
Below we show the applet ReadFileViaURL
that reads a text file. Note that we use the URL
class that we discussed in the previous section.
In this case, the URL
class provides a method to obtain file access via an InputStream
object.
//
Open a stream to the file using the URL.
try {
InputStream in=url.openStream
();
BufferedReader dis =
new BufferedReader
(new InputStreamReader (in));
fBuf = new StringBuffer ()
;
while ( (line = dis.readLine
()) != null) {
fBuf.append (line
+ "\n");
}
in.close ();
}
catch (IOException e) {
fTextArea.append ("IO Exception
= "+e);
System.out.println ("IO Exception
= "+e);
return;
}
We wrap this stream with an InputStreamReader
to provide proper character handling. We in turn wrap this stream
with an BufferedReader,
which provides buffering to smooth out the stream flow and also
contains the convenient readLine()
method that grabs an entire line and returns it as a string.
The program can also run as a standalone application.
We see in the readFile()
method how to obtain a URL
object from a File
object for local files.
ReadFileViaURL.java
Resources: data.txt
|
import
javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.net.*;
/** Demonstration of reading a local file with a URL **/
public class ReadFileViaURL extends JApplet
implements ActionListener
{
// A Swing text area for display of string
info
JTextArea fTextArea = null;
String fFileToRead ="data.txt";
StringBuffer fBuf = null;
// Flag for whether the applet is in a browser
// or running via the main () below.
boolean fInBrowser = true;
/** Build the GUI
* Create a User Interface with
a text area with scroll bars
* and a Go button to initiate
processing and a Clear button
* to clear the text area.
**/
public void init () {
Container content_pane = getContentPane
();
JPanel panel = new JPanel (new
BorderLayout ());
// Create a text area to display
file contents
fTextArea = new JTextArea ();
fTextArea.setEditable (false);
// Add to a scroll pane so that
a long list of
// computations can be seen.
JScrollPane area_scroll_pane =
new JScrollPane (fTextArea);
panel.add (area_scroll_pane,"Center");
JButton go_button = new JButton
("Go");
go_button.addActionListener (this);
JButton clear_button = new JButton
("Clear");
clear_button.addActionListener
(this);
JButton exit_button = new JButton
("Exit");
exit_button.addActionListener
(this);
JPanel control_panel = new JPanel
();
control_panel.add (go_button);
control_panel.add (clear_button);
control_panel.add (exit_button);
panel.add (control_panel,"South");
// Add text area with scrolling
to the contentPane.
content_pane.add (panel);
// If running in a browser, read
file name from
// applet tag param value. Else
use the default.
if (fInBrowser) {
// Get setup parameters
from applet html
String param = getParameter
("FileToRead");
if (param != null)
{
fFileToRead
= new String (param);
}
}
} // init
/** Use a URL object to read the file **/
public void readFile () {
String line;
URL url=null;
// Get the URL for the file.
try {
if (fInBrowser)
url =
new URL (getCodeBase (), fFileToRead );
else {
File
file = new File (fFileToRead);
if (file.exists
() )
url
= file.toURL ();
else {
fTextArea.append
("No file found");
System.out.println
("No file found");
System.exit
(0);
}
}
}
catch (MalformedURLException e)
{
fTextArea.append
("Malformed URL = "+e);
System.out.println
("Malformed URL= "+e);
return;
}
// Open a stream to the file using
the URL.
try {
InputStream in = url.openStream
();
BufferedReader dis
=
new BufferedReader
(new InputStreamReader (in));
fBuf = new StringBuffer ()
;
while ( (line = dis.readLine
()) != null) {
fBuf.append
(line + "\n");
}
in.close ();
}
catch (IOException e) {
fTextArea.append
("IO Exception = "+e);
System.out.println
("IO Exception = "+e);
return;
}
// Load the file into the TextArea.
fTextArea.append (fBuf.toString ());
} // readFile
/**
* Can use the start () method,
which is called after
* init () and the display has
been created.
**/
public void start () {
// Now read the file.
readFile ();
}
/** Respond to the buttons **/
public void actionPerformed (ActionEvent e)
{
String source = e.getActionCommand
();
if (source.equals ("Go"))
start
();
else if ( source.equals ("Clear")
)
fTextArea.setText
(null);
else
System.exit
(0);
} // actionPerformed
/** Display the println string on the text
area **/
public void println (String str) {
fTextArea.append (str + '\n');
}
/** Display the print string on the text area
**/
public void print (String str){
fTextArea.append (str);
}
/** Create the frame and add the applet to
it **/
public static void main (String[] args) {
int frame_width=200;
int frame_height=300;
// Create an instance of ReadFile_JApplet8
and add to the frame.
ReadFileViaURL applet = new ReadFileViaURL
();
applet.fInBrowser = false;
applet.init ();
// Following anonymous class used
to close window & exit program
JFrame f = new JFrame ("Read file
from URL Demo");
f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
// Add applet to the frame
f.getContentPane ().add ( applet);
f.setSize (new Dimension (frame_width,frame_height));
f.setVisible (true);
} // main
} // class ReadFileViaURL
|
The program can also run as a standalone application.
We see in the readFile()
method of ReadFile_JApplet8
how to obtain a URL
object from a File
object for local files.
Resources: