.
.
Java Technology Fundamentals Newsletter header
    April 2, 2004    

In this Issue

 

Welcome to the Java Developer Connection Java Technology Fundamentals Newsletter.

This monthly newsletter provides a way for you to learn the basics of the Java programming language, discover new resources, and keep up-to-date on the latest additions to the JDC's New to Java Programming Center.

- Java Programming Language Basics: Working with ZIP Files
- Java Bits: Threads in Applets (From the Java Tutorial)
- Making Sense of Java Classes: ProgressMonitor Class
- Program Challenge: Zip Files
- Sun's Online Courses: Object-Oriented Analysis and Design Using UML
- Tech Tips: Best Practices in Exception Handling
- Online Chats: Open Source APIs for Java Technology Games
- For More Information: Read articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

.

Java Programming Language Basics

Working with ZIP Files

ZIP files are a common format for archive files. These files are used to group multiple files together in one, and to compress each of those files with the goal that each compressed file takes up less space than the original.

JAR files are similar to ZIPs, but are specific to Java technology. Essentially, the files are the same format, but JAR files include a manifest to describe the contents, like which class in the JAR should be run to execute the contents.

Before exploring how to access these files from your Java programs, here is a little history of the ZIP format. In 1985, a program called ARC packaged multiple files together to be transmitted over the Fido network (a predecessor to the Internet) networking bulletin board systems (BBSs) together over dialup lines. They were 1200-2400 baud, really slow connections. Besides grouping multiple files together, these files were compressed, saving bandwidth and thus network charges, as there was no such thing as unlimited usage monthly connection Internet.

Phil Katz recoded ARC into assembler, called it PKARC. After adding more compression formats and renaming PKARC to PKZIP, the ZIP format became the standard it is today.

Support for accessing files in the ZIP format is done with classes found in the java.util.zip package. Added to the Java libraries with the 1.1 release, the key classes here are ZipEntry, ZipFile, ZipInputStream, and ZipOutputStream. For those prone to deal with exceptions, there's also the ZipException class.

Let us explore the ZipFile class for how to read entries from a ZIP file.

There are three constructors for the ZipFile class:

ZipFile(File file) 
ZipFile(File file, int mode) 
ZipFile(String name) 

The first two allow you to access a ZipFile from a File object, while the third creates a File from a String that designates the path to the ZIP file. Files are opened in read mode (constant OPEN_READ), unless the mode passed into the second constructor includes OPEN_DELETE. Setting the mode to delete means the ZIP file won't survive beyond the life of the virtual machine. Exactly when it will get deleted depends on the implementation of the virtual machine.

Creating a ZipFile just involves calling one of the constructors:

ZipFile zip = new ZipFile("example.zip");

Once you have a ZipFile, what can you do with it? Typically, you work with one of the entries inside the file. That is one of the files packaged inside it. The entries method returns an Enumeration so you can do just that.

  ZipFile zipfile = new ZipFile(name);
  Enumeration enum = zipfile.entries();
  while (enum.hasMoreElements()) {
    Object obj = enum.nextElement();
    System.out.println(obj);
  }

Each element of the returned Enumeration is a ZipEntry. You can also look up an entry by name through the getEntry(String name) method of ZipFile. Once you have a ZipEntry, you get the data associated with the ZipFile, along with the before and after sizes. This is demonstrated through the following program. Name at least one ZIP file on the command line.

  import java.io.*;
  import java.util.*;
  import java.util.zip.*;

  public class ListZip {
    public static void main(String args[]) {
      for (int i=0, n=args.length; i<n; i++) {
        String name = args[i];
        try {
        ZipFile zipfile = new ZipFile(name);
        Enumeration enum = zipfile.entries();
        while (enum.hasMoreElements()) {
          ZipEntry entry = (ZipEntry)enum.nextElement();
          System.out.println(
              entry.getName() + " / " +
              entry.getSize() + " / " +
              entry.getCompressedSize()
            );
        }
        } catch (IOException e) {
          System.err.println("Error accessing: " + name);
        }
        System.out.println();
      }
    }
  }

Getting access to a ZipEntry doesn't provide access to the underlying data. Instead, a ZipEntry works much like an entry in your file system directory. The data isn't there, only the names and numbers associated with that data.

In order to get access to the InputStream associated with an entry, you need to ask the ZipFile: getInputStream(ZipEntry entry). This then returns an InputStream that you can use to read the data.

To demonstrate, the following program takes three command line arguments.

  • Argument 1 is the name of the ZIP file to read
  • Argument 2 is the name of the entry you want to access
  • Argument 3 is the name of the extracted version of the entry

To help prevent losing valuable files, instead of overwriting a local file, you are required to explicitly state what file you want to save the copy to.

  import java.io.*;
  import java.util.*;
  import java.util.zip.*;

  public class GetFile {
    public static void main(String args[]) {
      if (args.length != 3) {
        System.err.println("Usage: java GetFile foo.zip name output");
      }
      String zipname = args[0];
      String entryname = args[1];
      String output = args[2];
      System.out.println("Copying " + entryname + " from " + 
          zipname + " into " + output);
      try {
        ZipFile zipfile = new ZipFile(zipname);
        ZipEntry entry = zipfile.getEntry(entryname);
        InputStream is = zipfile.getInputStream(entry);
        OutputStream os = new FileOutputStream(output);
        byte array[] = new byte[512];
        int length;
        while ((length = is.read(array)) != -1) {
          os.write(array, 0, length);
        }
        is.close();
        os.close();
      } catch (IOException e) {
        System.err.println("Error copying: " + zipname);
      }
    }
  }

As previously stated, JAR files are just like ZIP files. You can get a directory of its contents and a specific file in an identical manner. In addition to getting a ZipEntry with getEntry, you can also get a JarEntry with getJarEntry. JarEntry gets things like the manifest attributes and security certificates. You can also get the Manifest itself for the whole JarFile with the getManifest method.

Unlike the ZIP file-related classes, the JAR file-related ones are found in the java.util.jar package, except for the Certificate, which is found in java.security.cert.

Test what you learned about ZIP basics with this online quiz.

.
.

Java Bits

Threads in Applets (From the Java Tutorial)

Every applet can run in multiple threads. Applet drawing methods (paint and update) are always called from the AWT drawing and event handling thread. The threads that the major milestone methods -- init, start, stop, and destroy -- are called from depends on the application that's running the applet. But no application ever calls them from the AWT drawing and event handling thread.

Many browsers allocate a thread for each applet on a page, using that thread for all calls to the applet's major milestone methods. Some browsers allocate a thread group for each applet, so that it's easy to kill all the threads that belong to a particular applet. In any case, you're guaranteed that every thread that any of an applet's major milestone methods creates belongs to the same thread group.

Read more:

.
.

Making Sense of the Java Class

ProgressMonitor Class

Last month you learned to use JProgressBar and variations of that object. This month you're going to learn to use ProgressMonitor. The ProgressMonitor class allows you to create an object that provides a JProgressBar, which monitors the progress of an operation, letting users know the current state of that operation. You might use this object when your application is busy writing data to disk, reading from disk, performing calculations, and so forth.

In addition, ProgressMonitor allows you to provide useful information to the user so they know to wait for the operation to complete before attempting to do something more in the application.

You'll frequently place a ProgressMonitor in an event handler method. When the event is fired, the ProgressMonitor is triggered and begins to monitor the operation. Because you want the operation and the monitor to be two separate processes (one watching the other), you need to place ProgressMonitor in its own thread. (If you need a refresher on threads, see For More Information below.) Other processes are locked out from that thread and are not updated until after the code is completed. Then the Progress Monitor's progress bar is removed from the display.

The ProgressMonitor class is simple and straightforward with one constructor, and several useful methods.

When the ProgressMonitor is created, it is given a numeric range and a descriptive string. Create a ProgressMonitor object with this constructor:

ProgressMonitor(Component parentComponent, Object message, String note, int min, int max)

As the operation progresses, call the setProgress method to indicate how far along the [min,max] range the operation is. You set the range as a variable.

ProgressMonitor also gives the user the option of canceling an operation. This is done with the isCanceled method, which returns true when the Cancel button is clicked. To give the user a message about the progress of the operation, use the setNote method, which takes a String as an argument.

The following application demonstrates the concepts above by creating a process that simply counts to 100. A progress bar appears with a note reflects the current state of the process.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;



public class TestMonitor extends JFrame implements ActionListener {
	JButton rb;
	ProgressMonitor pm;
	AThread aThread = null;
	int maxCount = 100;


	public TestMonitor() {
          rb = new JButton("Run");
	  rb.addActionListener(this);
	  JPanel p = new JPanel();
	  p.add(rb);
	  getContentPane().add(p, BorderLayout.CENTER);

	  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	  setBounds(0, 100, 300, 300);
	  setVisible(true);
       }

	 public void actionPerformed(ActionEvent ae) {
	   aThread = new AThread();
	   aThread.start();
	}


	class AThread extends Thread {
	 public void run() {
         pm = new ProgressMonitor(rb, "Please Wait", 
                "Count is 0% finished",0, maxCount);
         for (int count = 0; count < maxCount; ++count) {
		pm.setProgress(count  + 1);
		double percent = 100.0 * (count + 1) / maxCount;
		pm.setNote("Count is " + (int) percent + "% complete");
		try {
			java.lang.Thread.sleep(100);
		} catch (InterruptedException e) {}

		if (pm.isCanceled()) {
			return;
			 }
		 }
	 }
 }

When this application is run, it should look something like the image below:

Progress Bars

.
.

Program Challenge

Create a graphical program that prompts the user to select a ZIP or JAR file. Upon selection, the data for each entry in the file is shown in a JTable. Be sure to show at least the name, original size, compressed size, and compression method.

See a possible solution to the Challenge.

.
.

Sun's Courses

Object-Oriented Analysis and Design Using UML

The Object-Oriented Analysis and Design Using UML course effectively combines instruction on software development processes, object-oriented technologies, and the Unified Modeling Language (UML). This instructor-led course uses lecture, group discussion, and facilitator-led activities (such as analyzing stakeholder interviews) to present one practical, complete, object-oriented analysis and design (OOAD) roadmap from requirements gathering to system deployment.
» Find out more:

.
.

Tech Tips: Best Practices in Exception Handling

Exception handling is a built-in aspect of the Java programming language. The concept of handling error cases with exceptions is designed to make code more reliable and easier to maintain and read. This tip looks at some best practices for dealing with and handling exceptions.

As a quick refresher, here's the full construct for exception handling:

   try {

     // code which could potentially
     // throw an exception

   } catch (TheException1 e) {

     // code to handle exceptional condition

   } catch (TheException2 e) {

     // code to handle next exceptional condition

   } finally {

     // code to run whether an exceptional 
    // condition happened or not
    
   }

Basically, code that might throw an exception goes within a try block. A specific catch block code runs only if the exception identified for it occurs (or its subclass). However, the code in the finally block runs under all conditions -- this even includes the case when the try-catch code calls return to exit out of the current method.

Read more:

.
.

Online Chats

Open Source APIs for Java Technology Games

Guests: Athomas Goldberg, Jeff Kesselman, Daniel Petersen, and Ken Russell

April 6. 11:00 A.M. PST/7:00 P.M. GMT

.
.

For More Information

.
.

Downloading the Java 2 Platform

For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the J2SE development kit.

.
.
.

Reader Feedback

  Very worth reading    Worth reading    Not worth reading 

If you have other comments or ideas for future newsletters, please type them here:

 

Have a question about Java programming? Use Java Online Support.

.
.

Find archived issues of the following Java technology developer newsletters or manage your current newsletter subscriptions: https://softwarereg.sun.com/registration/developer/en_US/subscriptions

Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:

- Core Java Technologies Newsletter. Learn about new products, tools, resources, and events of interest to developers working with core Java technologies.
- Wireless Developer Newsletter. Learn about the latest releases, tools, and resources for developers working on wireless and Java Card technologies and applications.
- Core Java Technologies Tech Tips (formerly JDC Tech Tips) Get expert tips, sample code solutions, and techniques for developing in the Java 2 Platform, Standard Edition (J2SE)
You can subscribe to these and other JDC publications on the JDC Newsletters and Publications page

PRIVACY STATEMENT:
Sun respects your online time and privacy. You have received this based on your e-mail preferences. If you would prefer not to receive this information, please follow the steps at the bottom of this message to unsubscribe.


IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html


Copyright 2004 Sun Microsystems, Inc. All rights reserved. 4150 Network Circle, Santa Clara, CA 95054

FEEDBACK
Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: dana.nourie@sun.com


SUBSCRIBE/UNSUBSCRIBE
- To subscribe, go to the subscriptions page, choose the newsletters you want to subscribe to and click Update
- To unsubscribe, go to the subscriptions page, uncheck the appropriate check box, and click Update


Trademark Information: http://www.sun.com/suntrademarks/
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.


Sun 
Microsystems, Inc.
image
image