Good morning,

I would like to ask for your help, I am working on getting a text file read using using a java applet, the content of that text file is generated with an object in the class TowersOfHanoiExecute
TowersOfHanoi towersOfHanoi = new TowersOfHanoi( totalDisks );

after which I was planning to use line 23 and 24 in the TowersOfHanoiExecute class
readFileApplet myreadFileApplet = new readFileApplet();
myreadFileApplet.readFile();

to read the text file into the Applet.

unfortunatly here is the error message I get:
Exception in thread "main" java.lang.NullPointerException
at java.applet.Applet.getCodeBase(Applet.java:152)
at readFileApplet.readFile(readFileApplet.java:26)
at TowersOfHanoiExecute.main(TowersOfHanoiExecute.java:24)

I think line 23 and 24 in the TowersOfHanoiExecute class is where my problem is , but I really have no idea why?
Could somebody pelase help me figure it out.
Thanks
John

The classes:
TowersOfHanoiExecute.java class

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class TowersOfHanoiExecute 
{
	
	public static void main(String[] args) 
	{// TODO Auto-generated method stub
		
    	int startPeg = 1; //Value 1 is used to indicate startPeg in output
		int endPeg = 3; //Value 3 is used to indicate endPeg in output
		int tempPeg = 2; //Value 2 is used to indicate tempPeg in output
		int totalDisks = 3; //number of disks
		System.out.println("TowerOfHanoi text file has been created"); 
		TowersOfHanoi towersOfHanoi = new TowersOfHanoi( totalDisks );
	   
		//read into applet
		readFileApplet myreadFileApplet = new readFileApplet();
		myreadFileApplet.readFile();		
	
		PrintStream stdOut=null; 

		try 
		{ 
		stdOut = new PrintStream(new FileOutputStream ("TowerOfHanoi.txt"));
		} catch (FileNotFoundException e) { 
		e.printStackTrace(); 
		} 
		System.setOut(stdOut);
		

		//initial nonrecursive call: move all disks.
		towersOfHanoi.solveTowers( totalDisks, startPeg, endPeg, tempPeg );
		

		
		
		
	}//end main

}//end class TowersofHanoiExecute

class: Towers Of Hanoi

public class TowersOfHanoi
{
	private int numDisks;//Variable representing the number of disks to move
	
	public TowersOfHanoi( int Disks )
	{
		int disks = 0;
		setNumDisks(disks);
	} //end TowersOfHanoi constructor
	
	// Recursively move the disks through the towers
	public void solveTowers( int disks, int sourcePeg, int destinationPeg,
	int tempPeg)
	{
		try
		{
    		//Base case -- only one disk to move
    		if ( disks == 1 )
    		{
    			//instead of the system.out.printf use the textArea.append
    		    System.out.printf( "\n%d --> %d\r", sourcePeg, destinationPeg );
    			return;
    		} //end if
    		
    		//recursion step -- move disk to tempPeg, then to destinationPeg
    		//move(disk -1) disks from sourcePeg to tempPeg recursively
    		solveTowers( disks - 1, sourcePeg, tempPeg, destinationPeg );
    		
    		//move the last disk from the sourcePeg to the destinatinPeg
    		System.out.printf( "\n%d --> %d\r", sourcePeg, destinationPeg );
    		
    		// Move(disk-1) disks from tempPeg to destinationPeg
    		solveTowers( disks - 1, tempPeg, destinationPeg, sourcePeg );
		}  	
        catch (Exception e)
        {
        System.out.println(e.getMessage());
        }
    }//end solveTowers
	public void setNumDisks(int numDisks) 
	{
		this.numDisks = numDisks;
	}//end setNumDisks

	public int getNumDisks()
	{
		return numDisks;
	}//getNumDisks
}//end class TowersOfHanoi

class: FileViewer

import java.awt.Button;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * This class creates and displays a window containing a TextArea, in which the
 * contents of a text file are displayed.
 */
@SuppressWarnings("serial")
public class FileViewer extends Frame implements ActionListener {
  String directory; // The default directory to display in the FileDialog

  TextArea textarea; // The area to display the file contents into

  /** Convenience constructor: file viewer starts out blank */
  public FileViewer() {
    this(null, null);
  }

  /** Convenience constructor: display file from current directory */
  public FileViewer(String filename) {
    this(null, filename);
  }

  /**
   * The real constructor. Create a FileViewer object to display the specified
   * file from the specified directory
   */
  public FileViewer(String directory, String filename) {
    super(); // Create the frame

    // Destroy the window when the user requests it
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        dispose();
      }
    });

    // Create a TextArea to display the contents of the file in
    textarea = new TextArea("", 24, 80);
    textarea.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
    textarea.setEditable(false);
    this.add("Center", textarea);

    // Create a bottom panel to hold a couple of buttons in
    Panel p = new Panel();
    p.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 5));
    this.add(p, "South");

    // Create the buttons and arrange to handle button clicks
    Font font = new Font("SansSerif", Font.BOLD, 14);
    Button openfile = new Button("Open File");
    Button close = new Button("Close");
    openfile.addActionListener(this);
    openfile.setActionCommand("open");
    openfile.setFont(font);
    close.addActionListener(this);
    close.setActionCommand("close");
    close.setFont(font);
    p.add(openfile);
    p.add(close);

    this.pack();

    // Figure out the directory, from filename or current dir, if necessary
    if (directory == null) {
      File f;
      if ((filename != null) && (f = new File(filename)).isAbsolute()) {
        directory = f.getParent();
        filename = f.getName();
      } else
        directory = System.getProperty("user.dir");
    }

    this.directory = directory; // Remember the directory, for FileDialog
    setFile(directory, filename); // Now load and display the file
  }

  /**
   * Load and display the specified file from the specified directory
   */
  public void setFile(String directory, String filename) {
    if ((filename == null) || (filename.length() == 0))
      return;
    File f;
    FileReader in = null;
    // Read and display the file contents. Since we're reading text, we
    // use a FileReader instead of a FileInputStream.
    try {
      f = new File(directory, filename); // Create a file object
      in = new FileReader(f); // And a char stream to read it
      char[] buffer = new char[4096]; // Read 4K characters at a time
      int len; // How many chars read each time
      textarea.setText(""); // Clear the text area
      while ((len = in.read(buffer)) != -1) { // Read a batch of chars
        String s = new String(buffer, 0, len); // Convert to a string
        textarea.append(s); // And display them
      }
      this.setTitle("FileViewer: " + filename); // Set the window title
      textarea.setCaretPosition(0); // Go to start of file
    }
    // Display messages if something goes wrong
    catch (IOException e) {
      textarea.setText(e.getClass().getName() + ": " + e.getMessage());
      this.setTitle("FileViewer: " + filename + ": I/O Exception");
    }
    // Always be sure to close the input stream!
    finally {
      try {
        if (in != null)
          in.close();
      } catch (IOException e) {
      }
    }
  }

  /**
   * Handle button clicks
   */
  @SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
    String cmd = e.getActionCommand();
    if (cmd.equals("open")) { // If user clicked "Open" button
      // Create a file dialog box to prompt for a new file to display
      FileDialog f = new FileDialog(this, "Open File", FileDialog.LOAD);
      f.setDirectory(directory); // Set the default directory

      // Display the dialog and wait for the user's response
      f.show();

      directory = f.getDirectory(); // Remember new default directory
      setFile(directory, f.getFile()); // Load and display selection
      f.dispose(); // Get rid of the dialog box
    } else if (cmd.equals("close")) // If user clicked "Close" button
      this.dispose(); // then close the window
  }

  /**
   * The FileViewer can be used by other classes, or it can be used standalone
   * with this main() method.
   */
  @SuppressWarnings("deprecation")
static public void main(String[] args) throws IOException {
    // Create a FileViewer object
    Frame f = new FileViewer((args.length == 1) ? args[0] : null);
    // Arrange to exit when the FileViewer window closes
    f.addWindowListener(new WindowAdapter() {
      public void windowClosed(WindowEvent e) {
        System.exit(0);
      }
    });
    // And pop the window up
    f.show();
  }
}

Recommended Answers

All 13 Replies

You are probably getting this error because you are trying to do an action on an object that is 'null'. I would add an if statement saying

if (myObjects == null){
System.out.println("this was null");

That will help you find what may be causing the problem. When I try to compile what you have given I get a compalation error "cannot find symbol class readFileApplet." Otherwise I would try to help more. I guess that is probably because I haven't messed with applets before (maybe I'm not set up for it??).

readFileApplet.class seems to be missing at runtime

I don't think that you need to do any special setup for applets.
I'm surprised that you get a compilation error because here it trys to run through.
By the way I am using:
Eclipse
Version: 3.4.2

Maybe in the copying and pasting something was lost. I am attaching the actual java files this time.

I'm going to try your suggestion and see.

Thank you for your help
John

I did the follwoing change:

//read into applet
readFileApplet myreadFileApplet = new readFileApplet();
myreadFileApplet.readFile();        
if (myreadFileApplet == null)
{System.out.println("this was null");}

and also like this:

//read into applet
readFileApplet myreadFileApplet = new readFileApplet();
if (myreadFileApplet == null)
{System.out.println("this was null");}
myreadFileApplet.readFile();

However both game me the same error message:

Exception in thread "main" java.lang.NullPointerException
    at java.applet.Applet.getCodeBase(Applet.java:152)
    at readFileApplet.readFile(readFileApplet.java:26)
    at TowersOfHanoiExecute.main(TowersOfHanoiExecute.java:19)

thanks for your help

I did another test a little bit different to see if the object was not null.
The code I used line 17 to 21 in the TowersOfHanoiExecute class:

//read into applet
readFileApplet myreadFileApplet = new readFileApplet();
if (myreadFileApplet != null)
{System.out.println("myreadFileApplet was NOT null");}
myreadFileApplet.readFile();

Here is my error message:

myreadFileApplet was NOT null
Exception in thread "main" java.lang.NullPointerException
    at java.applet.Applet.getCodeBase(Applet.java:152)
    at readFileApplet.readFile(readFileApplet.java:26)
    at TowersOfHanoiExecute.main(TowersOfHanoiExecute.java:21)

so it appears as my myreadFileApplet object is NOT null but I still have the same problem.

The error is being thrown at line 26 of readFileApplet.java by the method getCodeBase() .
I don't know for sure why. I haven't used URL or getCodeBase() before. Sun's documentation states that it get the url that the applet is located, is the file in the inappropriate place possibly?

I don't see where the TowerOfHanoi.txt file was created. Is that a file on the server? If the file wasn't made, or isn't there correctly that could cause the error to be thrown.

Some people online have suggested using getDocumentBase() instead of getCodeBase() . (I don't know if that would help though)

this link may help http://www.codingforums.com/showthread.php?t=53441

I have been working on trying to figur out where my problem is located, and in so doing I found out that if I have the code:
readFileApplet myreadFileApplet = new readFileApplet();
myreadFileApplet.readFile();

in place that my text file never really gets created, however the old one is still there and that should be read by the Applet reader shouldn't it?

Thanks

Thanks PopeJarth, I apologize I just saw response.
The text file is created line 28 of class TowersOfHanoiExecute, I had the mistake already of not having hte file present and it gave me a different error message along the lines of file not found.
Thanks for the info and link I am looking at them now

I just tried the getDocumentBase instead of hte getCodeBase but it still gave me the same error message :(

At this point I am probably as confused as you. =(

Do you think it makes a difference if the applet is run on your pc or on a web server? The getCodeBase() method may give an error from the folder structure on your pc???

Well the readFileApplet class functions correctly by itself.
If I just execute it, making sure my "TowerOfHanoi.txt" file is in the "bin" folder. I get the applet that opens and displays the file content.

The only time I get the error messages is when I invoke it as an object using the code.
readFileApplet myreadFileApplet = new readFileApplet();
myreadFileApplet.init();
myreadFileApplet.readFile();

Here I tried to initialize it before reading the file but it didn't change a thing, I still got the:

Exception in thread "main" java.lang.NullPointerException
at java.applet.Applet.getParameter(Applet.java:174)
at readFileApplet.init(readFileApplet.java:17)
at TowersOfHanoiExecute.main(TowersOfHanoiExecute.java:17)

Thanks for looking at it with me

I beleive I found the problem, apparently an applet can not be launch as a method with a new object.
Could somebody please enlightened me, and let me know how I would do something similar to new object but for applets?

thanks

I found that the real problem is that I can't launch an applet like I would another class or method with just creating a new object.

Would somebody know of a work around, I did some research o nthe net, but the problem is that I am using a get.parameter with my applet and JFrame doesn't have the equivalent, I tried using the JFrame system.getProperties but that didn't work.

thank you for any suggestions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.