Sun Java Solaris Communities My SDN Account Join SDN
 
Java Technology Fundamentals Newsletter Index

New-to-Java Programming Center Supplement

 

New-to-Java Programming Center
Programming Center Supplement

Welcome to the Java Developer ConnectionSM New to Java Programming Center Supplement!

This monthly supplement 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 JavaTM Programming Center.

CONTENTS

1. Java Programming Language Basics

Exceptions and How to Handle Them

2. Making Sense of the Java Class Libraries

FileInputStream and FileOutputStream

3. Program Challenge

CopyFile

4. Java Bits

Java 2 Platform, Standard Edition (J2SE) versus Java 2 Platform, Enterprise Edition(J2EE) What's the difference?

5. New to the New to Java Programming Center

Building an Application, Part 2

6. For More Information

Links to articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

7. Program Challenge Solution and Explanation

Possible solution to the CopyFile program

Java Programming Language Basics

Exceptions and How to Handle Them

If you look at the list of keywords for the Java programming language, you might think someone was into sports with keywords like throw, throws, and catch. Add in try and finally, and you have everything necessary for the Java virtual machine (JVM)1 to signal errors or exceptions in your programs. This is better known as exception handling.

Defining the Terminology:

  • An exception is a signal to the virtual machine that something is wrong.
  • When an exception occurs, it is thrown, interrupting the normal sequence of operations.
  • A thrown exception can be caught, transferring control to a new point in the program.

These are the basics of exception handling, provided you put the keywords together properly. And putting them together properly is what the rest of this article is about.

Exception handling is done with a try-catch block. The code that might throw an exception is placed within the try block. You provide catch blocks for each exception type you're interested in or required to handle based upon the methods used within the try clause. The framework of the syntax for such a block is as follows:

try {
   // code which might throw exceptions
} catch (ExceptionType1 exceptionVar) {
   // code to handle ExceptionType1
   // exceptionVar is local to catch block
} catch (ExceptionType2 exceptionVar) {
   // code to handle ExceptionType2
   // exceptionVar is local to catch block
}


When multiple catch clauses are present, control transfers to the first exception type that matches the thrown exception.

For instance, if your exception types are FileNotFoundException and IOException, in that order, and a FileNotFoundException exception is thrown, then only the exception handling code for the FileNotFoundException exception type is executed. If, however, an EOFException is thrown, then only the IOException handling code executes, since EOFException is a subclass of IOException.

Here is an example using specific exception types, which is the framework for reading from a file.

try {
   // Open file.
   FileInputStream fis = new FileInputStream(filename);
   // Read from fis.
   ...
   // Close file.
   fis.close();
} catch (FileNotFoundException exception) {
   System.err.println("Error opening file: " + 
                                    filename);
} catch (IOException exception) {
   System.err.println("Error accessing file: " + 
                                    filename);
} 

There is one small problem with the above code. If an exception is thrown while reading from the file, the FileInputStream isn't immediately closed. It is eventually closed when the variable is garbage collected, but it is best to free resources like files as soon as possible, and not wait until the garbage collector decides to free space.

Overcoming this problem requires the use of the finally keyword. The finally clause is an optional block to a try-catch block that always executes, whether or not there was an exception. To overcome the this problem, move the fis.close call into a new finally block:

// Declare variable so that it is accessible 
// within finally block.
FileInputStream fis = null;
try {
   // Open file.
   fis = new FileInputStream(filename);
   // read from fis
   ...
} catch (FileNotFoundException exception) {
   System.err.println("Error opening file: " + 
                                    filename);
} catch (IOException exception) {
   System.err.println("Error accessing file: " + 
                                      filename);
} finally {
   if (fis != null) {
     try {
       // Close file.
       fis.close();
     } catch (IOException ignored) {
     }
   }
} 

Notice that the fis.close call is in a try-catch block, too. That's because close can throw an exception. In this particular case, if close fails, there is no way to recover, so the exception is just ignored.

Until you learn the libraries, the compiler will tell you when you aren't catching an exception. Then you just go back and put the appropriate code block within a try-catch block. Recompile, and you'll be all set.

Making Sense of the Java Class Libraries

FileInputStream and FileOutputStream

The Java API provides a number of classes that allow you to create applications that read and write to files. Two of the more popular classes are FileInputStream and FileOutputStream. They create byte streams linked to files.

Both FileInputStream and FileOutputStream are found in the java.io package, and are subclasses of the InputStream and OutputStream respectively. They inherit useful methods:

  • read (From InputStream) There are three versions of the read method, all of which read byte data from the input stream.
  • write (From OutputStream) There are three versions of the write method, all of which write to the invoking output stream.
  • flush (From OutputStream) The flush method forces data held in the buffer to be written to the invoking output stream.
  • close(From OutputStream and InputStream) The close method closes the invoking output stream and releases any resources allocated to it.

Reading and writing to files takes only five steps:

  1. Import the java.io package.
  2. Create a stream input object.
  3. Create a stream output object.
  4. Call methods for reading and writing.
  5. Close the stream objects with the close method.

To create a stream object, call one of the following constructors:

FileInputStream:

  • FileInputStream (String filename)
  • FileInputStream (File file)
  • FileInputStream (FileDescriptor desc)

FileOutputStream:

  • FileOutputStream (String filename)
  • FileOutputStream (String filename, boolean append)
  • FileOutputStream (File file)
  • FileOutputStream (FileDescriptor desc)

To read a file, create a stream object of type FileInputStream, then call the read method.

To write to a file, you create a stream object of type FileOutputStream, then call the write method.

The following example demonstrates:

  • Creating input and output stream objects
  • Reading and writing bytes from and to files
import java.io.*;
public class FileReaderWriterExample
{
  public static void main(String[] args) 
                     throws IOException
   {
      // Create input stream object.
     FileInputStream fis = 
        new FileInputStream("Data");
     // Create output stream object.
     FileOutputStream fout = 
        new FileOutputStream("Data2");
     
     // Set variable for looping through bytes.
     int c;
     // Loop to read and write bytes.
     while ((c = fis.read()) != -1)
        fout.write(c);
     // Close output and input resources. 
     fis.close();
     fout.close();
    }
}

This example reads and writes to files, but it does not account for the errors that frequently arise when dealing with files, such as non-existing files, files that are write-protected, and so forth.

To deal with possible errors, enclose the code in try-catch blocks, and throw exceptions where needed, as described in the previous section.

In addition to the FileInputStream and FileOutputStream classes, the java.io package has many other classes you can use for reading and writing to files. Read the documentation for the I/O package, and experiment, using different classes.

Also, study the hierarchy of the stream classes. There are many useful inherited methods available, depending which classes you choose to use in your applications.

See For More Information below.

Program Challenge: CopyFile

Use what you've learned about exception handling and reading and writing to files to create a CopyFile Program Challenge:

  1. Create a program that copies a file and writes it to another.

    It should accept two arguments:
    • The first argument is the input filename.
    • The second is the output filename.


  2. Enclose code in try-catch blocks.
  3. Catch the specific exceptions thrown.
  4. Display the appropriate error messages.

Java Bits:

Java 2 Platform, Standard Edition (J2SE) versus Java 2 Platform, Enterprise Edition (J2EE) What's the difference?

There are many Java technologies, and understanding the differences between the various platforms, such as J2SE and J2EE, can be confusing. Which do you need, how do they overlap, do you need both? The answer to these questions lies in what kind of project you're working on.

The J2SE platform includes the compiler and other tools, the JVM, and the core classes. Core classes provide programmers with the capability to create simple and complex applets and applications in which they may include the following:

  • Graphical User Interface Provided through the AWT and Swing libraries.
  • Basic Input and Output functionality Printing to the screen, a GUI, or to files is provided by the java.io package.
  • Database Connectivity This is referred to as JDBC technology and includes classes from the java.sql package
  • Internationalization character handling in J2SE 1.4 is based on version 3.0
  • of the Unicode standard.
  • Process XML This is a new feature of J2SE 1.4.

In addition, J2SE provides classes that make it possible to do networking, create beans, work with dates and mathematical functions, provide additional security, use collections, and much more.

The J2EE platform works with J2SE, extending the these technologies by providing the following services:

  • Use of Java servlets
  • Dynamic HTML pages through JavaServer Pages technology
  • Enterprise JavaBeans components
  • Database connectivity, referred to as JDBC technology and includes classes from the java.sql package
  • XML technology
  • Tools for deployment

To set up the J2EE platform, you must have J2SE installed. J2EE defines the standard for developing multitier enterprise applications, and ensures portability of applications across the wide range of existing enterprise systems capable of supporting J2EE.

On the other hand, you can use some of the above technologies without installing the J2EE platform.

For instance, you can make use of Java servlets by installing J2SE and a servlet engine like Tomcat. In addition, Tomcat also processes JavaServer pages.

For standalone applications, you likely only need:

  • The J2SE platform, which is the J2SE download.

To create web applications, using servlets or JSP Pages, you need to install:

  • J2SE platform, the J2SE download.
  • A servlet engine such as Tomcat.

To build enterprise applications that require use of EJBs, servlets, JSP pages, XML, and database connectivity, you need:

  • The J2SE download
  • The J2EE download, which includes the Cloudscape database and the engine for servlets and JavaServer Pages, and containers for EJBs.

In addition to these two Java platforms, there are other Java technologies. You can download additional Java platforms such as Java 2 Platform, Micro Edition (J2ME) for wireless functionality, or optional software such as Java Web Start, which makes it possible to launch applications from a web page.

In summary, J2SE provides a lot of functionality to applets and applications, while J2EE extends the platform to include enterprise web services, deployment tools, and more.

See For More Information.

New to the Programming Center

Building an Application, Part 2

Part 2 of this tutorial series introduces inheritance, image and text objects, and arranging those objects using a layout manager.

Building an Application, Part 1 now also available in

For More Information

Exception Handling Statements

Exception Handling

Lesson: I/O: Reading and Writing (but no 'rithmetic)

Class FilterInputStream

Class FileOutputStream

Java 2 Platform, Standard Edition Product Family

J2SE, version 1.4 Summary of New Features and Enhancements

The J2EE Tutorial

JavaServer Pages Tomcat @ Jakarta

Unraveling Java Technologies

New to Java Programming Center Building an Application Introduction

Program Challenge Solution

This is one possible solution to the Program Challenge:

import java.io.*;

public class CopyFile {
   public static void main(String args[]) {
     // Check for two command line arguments
     if (args.length != 2) {
       System.out.println(
         "Improper arguments use:" +
           " java CopyFile infile outfile");
       System.exit(-1);
     }

     // Get infile argument
     String infile = args[0];

     // Get outfile argument
     String outfile = args[1];

     // Create variables for in/out streams
     FileInputStream fis = null;
     FileOutputStream fos = null;

     try {
       // Create in stream
       fis = new FileInputStream(infile);

       // Create out stream
       fos = new FileOutputStream(outfile);
       
      // Declare variable for each byte read
       int ch;

       // Read byte til end of file
       while ((ch = fis.read()) != -1) {
       

         // Put bytes read into out stream
         fos.write(ch);
       }

     // Catch FileNotFoundException
     } catch (FileNotFoundException e) {
       System.err.println("File not found: " + e);

     // Catch IOException
     } catch (IOException e) {
       System.err.println("I/O problems: " + e);

     // Close files
     } finally {
       if (fis != null) {
         try {
           fis.close();
         } catch (IOException ignored) {
         }
       }
       if (fos != null) {
         try {
           fos.close();
         } catch (IOException ignored) {
         }
       }
     }
   }
}

Downloading the Java 2 Platform

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

IMPORTANT: Please read our Terms of Use and Privacy policies:

Have a question about programming? Use Java Online Support.

- Note -

Sun respects your online time and privacy. The Java Developer Connection mailing lists are used for internal Sun Microsystems purposes only. You have received this email because you elected to subscribe.

- Unsubscribe -

To unsubscribe to this newsletter, go to the subscriptions page uncheck the "JDC New-to-Java Supplement" checkbox, and click "Update".

- Subscribe -

To subscribe to other JDC mailings, go to the subscriptions page choose the newsletters you want to subscribe, and click "Update".

- Feedback -

Comments? Send your feedback on the JDC Newsletter to: jdc-webmaster

- Copyright -

Copyright 2001 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA

This document is protected by copyright.

JDC New-to-Java Programming Center Supplement
December 2001

Sun, Sun Microsystems, Java, and J2SE are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.


1 As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.