March 2006 Java Technology Fundamentals Newsletter

You are receiving this e-mail {e-mail address} because you elected to receive e-mail from Sun Microsystems, Inc. To update your communications preferences, please see the link at the bottom of this message. We respect your privacy and post our privacy policy prominently on our Web site http://sun.com/privacy/

Please do not reply to the mailed version of the newsletter, this alias is not monitored. Feedback options are listed in the footer for both content and delivery issues.
  Welcome to the Java Technology Fundamentals Newsletter.
Java Technology Fundamentals
NEWSLETTER
March 2006
 

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 Sun Developer Network's New to Java Center.

You can receive future issues of this newsletter in HTML or text:
http://developer.java.sun.com/subscription/

Note: For the code in this issue of Fundamentals to compile, you need to use the JDK 5.0 software.
http://java.sun.com/j2se/1.5.0/download.jsp

Contents
 
? Java Programming Language Basics: Working With the File Class
? Making Sense of the Java Classes & Tools: Package java.util.concurrent
? Java Bits: The Life Cycle of an Object
? What's New on Java Studio Creator: Using Page Fragments
? Tutorials and Tips From NetBeans.org: Derby Tutorial
? Sun's Java Technology Courses
? Program Challenge
? Free Developer Tools
? For More Information

Java Programming Language Basics
 
Working With the File Class


The filing system is one of the most basic services that an operating system provides to applications. Historically, it was one of the very first services to be developed. During the 1950s, the ability of a computer to automatically locate and load a program into its memory was not something computer programmers could take for granted.

Today, all filing systems allow a hierarchical directory structure of arbitrary depth to organize files of almost equally arbitrary length (4 GB is a common limit per file). File names identify files and are usually limited to anywhere from 32 to 256 characters in length. Although all filing systems are essentially identical in terms of these basic services, their exact implementations make them mutually incompatible.

To shield applications from this incompatibility obstacle, the File class defines platform-independent methods for manipulating a file maintained by a native filing system.
- File()    Constructs a File object

- canRead()
  canWrite()    Returns indication of whether file is readable or 
                writable

- compareTo()    Checks for ordering between file paths

- createNewFile()    Creates empty file if nonexistent

- createTempFile()    Creates empty file in special directory

- delete()    Removes file from file system

- deleteOnExit()    Causes file to be removed from file system when 
                    program ends without error

- equals()    Checks for equality between file objects (not contents)

- exists()    Returns indication of whether file exists

- getAbsoluteFile()
  getAbsolutePath()    Returns complete path to file

- getCanonicalFile()
  getCanonicalPath()    Returns complete path to file with no 
                        relative indicators

- getName()    Returns name of file

- getParent()
  getParentFile()    Returns parent directory for file

- getPath()    Returns file as a potentially relative path

- hashCode()    Returns hash code for file

- isAbsolute()
  isDirectory()
  isFile()
  isHidden()    Returns indicator status for file type

- lastModified()    Returns last modified timestamp

- length()    Returns size of file

- list()
  listFiles()    Returns list of files and directories in file

- listRoots()    Returns list of root filesystems

- mkdir()    Creates directory named by file

- mkdirs()    Creates directory and complete path as necessary named 
              by file

- renameTo()    Renames files

- setLastModified()    Changes last modified timestamp

- setReadOnly()    Changes file to read-only

- toString()    Returns string representation of file state

- toURI()
  toURL()    Constructs URI/URL for file
As you can see from the list of supported methods, class File does not allow you to access the file's contents. There are no read() or write() methods of File to let you do this. Class File primarily names files, queries file attributes, and manipulates directories or temporary files, all in a system-independent way. The following is a description of what you can do with files without opening them.

First off is the toURL() method. Don't use it. With version 6 of the Java Platform, Standard Edition (Java SE, formerly referred to as J2SE), the method becomes deprecated. Stop using it now. Basically, it doesn't properly escape characters that are illegal in URLs. Instead, if you need a URL, first get the URI, then convert the URI to a URL, as in fileVariable.toURI().toURL().

Naming Files

Files are named in one of two ways. You can either provide both a directory and a file within the directory, or you can provide both combined into one value. Either way, you are providing the full name of a file you wish to access. The benefit of providing a directory and file name separately is that you don't have to worry about how to combine the two. For instance, on Microsoft Windows-based platforms, the separator character is the backward slash character (\). On UNIX platforms, it is the foreward slash character (/). Although you can ask the File class what the separator character is through the separator class variable, you can now save yourself the bother of combining the two terms because the constructor of the File class can do it for you.

To demonstrate, the following code fragment attempts to create three File objects. Each line does succeed in creating a File object. However, if you try to use the File object, only the second or third attempts will succeed on all platforms, because they do not have a file separator value hard-coded into the source code.
  File f1 = new File("sun/microsystems");
  File f2 = new File("sun", "microsystems");
  File f3 = new File(new File("sun"), "microsystems");
Querying File Attributes

Class File provides a handful of methods for querying a minimal set of file attributes:
  • Whether the file exists
  • Whether the file is read protected
  • Whether the file is write protected
  • Whether the file is, in fact, a directory
  • Whether the file is hidden
  • Whether the file is specified as an absolute location
Discovering other common file attributes, such as whether a file is a system or an archived file, is not supported. As they did with the Java platform's AWT classes, the designers of these classes have taken the least common denominator of all filing systems for their model. If Java technology included features (such as an archived attribute) that some systems did not support, its universal compatibility across platforms would be jeopardized.

The following program shows how to use a File instance to query a file's attributes. The file is specified as a command-line parameter:
import java.io.*;
public class Attr {
  public static void main (String args[]) {
    File path = new File(args[0]);  // grab command-line argument
    String exists   = getYesNo(path.exists());
    String canRead  = getYesNo(path.canRead());
    String canWrite = getYesNo(path.canWrite());
    String isFile   = getYesNo(path.isFile());
    String isHid    = getYesNo(path.isHidden());
    String isDir    = getYesNo(path.isDirectory());
    String isAbs    = getYesNo(path.isAbsolute());
    System.out.println("File attributes for '" + args[0] + "'");
    System.out.println("Exists        : " + exists);
    if (path.exists()) {
      System.out.println("Readable      : " + canRead);
      System.out.println("Writable      : " + canWrite);
      System.out.println("Is directory  : " + isDir);
      System.out.println("Is file       : " + isFile);
      System.out.println("Is hidden     : " + isHid);
      System.out.println("Absolute path : " + isAbs);
    }
  }
  private static String getYesNo(boolean b) {
    return (b ? "Yes" : "No");
  }
}
You can experiment with this program by passing it various file names and directory names, either relative or absolute. An absolute file name would be one that started at the root level of the file system, such as C:\. Of course, although C:\ is absolute, it is not a file. The path of the directory at that level would be C:\., where the dot (.) specifies the directory file.

With J2SE 5.0, you can set only the readable attribute. Java SE 6 exposes the writable and executable attributes as well.

Manipulating Directories

A handier program would be one that could list the contents of a directory, as the dir or ls commands do in most operating systems. Fortunately, class File supports directory-list generation through its list() and listFiles() methods. Here's another program that recursively (that is, calling upon itself) lists directories and their contents:
import java.io.*;
import java.util.*;
public class Dir {
  static int indentLevel = -1;
  static void listPath(File path) {
    File files[];  // list of files in a directory
    indentLevel++; // going down...
    // Create list of files in this dir.
    files = path.listFiles();
    // Sort with help of Collections API.
    Arrays.sort(files);
    for (int i=0, n=files.length; i < n; i++) {
      for (int indent=0; indent < indentLevel; indent++) {
        System.out.print("    ");
      }
      System.out.println(files[i].toString());
      if (files[i].isDirectory()) {
        // Recursively descend dir tree.
        listPath(files[i]);
      }
    }
    indentLevel--; // And going up
  }
  public static void main (String args[]) {
    listPath(new File(args[0]));
  }
}
The program relies on a couple of interesting concepts. First of all, it calls itself recursively in the statement listPath(files[i]). This repeated invocation of the listPath() method restarts listPath() with a new path, initialized to contain the deeper directory to list.

The directory listing is sorted with the help of the Arrays class. By default, entries in a directory are unordered. To highlight the current directory level, the contents of a directory are indented according to its nesting level in the filing hierarchy. The depth of the recursion level, tracked in the class variable indentLevel, determines this nesting level. When a method exits, class variables are not destroyed the way simple method variables are. The program relies on this behavior to track the recursion level across multiple invocations of listPath().

Manipulating Temporary Files

One nice feature of the File class is its support for temporary files. Thanks to the static createTempFile() methods and the java.io.tmpdir system property, you can guarantee that the File object created by the method did not previously exist. Also, by calling deleteOnExit(), you can ensure that the file will be deleted if the Java environment ends naturally. The general framework for usage follows:
  File temp = File.createTempFile("sun", ".tmp"); // Prefix and suffix
  temp.deleteOnExit();
  // Use like any other File.
Summary

That's really all there is to File in J2SE 5.0. Java SE 6 adds a few more features such as getting free and total space on a disk partition, but functionally, the class never opens a file directly. It just accesses and manipulates the directory information.


Making Sense of the Java Classes & Tools
 
Package java.util.concurrent


Utility classes are commonly useful in concurrent programming. This package includes a few small standardized extensible frameworks, as well as some classes that provide useful functionality and are otherwise tedious or difficult to implement. Here are brief descriptions of the main components.

Interfaces. Executor is a simple standardized interface for defining custom threadlike subsystems, including thread pools, asynchronous IO, and lightweight task frameworks. Depending on which concrete Executor class is being used, tasks may execute in a newly created thread, in an existing task-execution thread, or in the thread calling execute(). Tasks may execute sequentially or concurrently. ExecutorService provides a more complete asynchronous task-execution framework. An ExecutorService manages queuing and scheduling of tasks, and it allows controlled shutdown. The ScheduledExecutorService subinterface adds support for delayed and periodic task execution. ExecutorServices provide methods that arrange asynchronous execution of any function expressed as Callable, the result-bearing analog of Runnable. A Future returns the results of a function, allows determination of whether execution has completed, and provides a means to cancel execution.

Implementations. Classes ThreadPoolExecutor and ScheduledThreadPoolExecutor provide tunable, flexible thread pools. The Executors class provides factory methods for the most common kinds and configurations of Executors, as well as a few utility methods for using them. Other utilities based on Executors include the concrete class FutureTask, which provides a common extensible implementation of Futures, and ExecutorCompletionService, which assists in coordinating the processing of groups of asynchronous tasks.

Read the rest of this article.

Java Bits
 
The Life Cycle of an Object


A typical Java technology program creates many objects that interact by sending messages. Through these object interactions, a program can carry out various tasks, such as implementing a graphical user interface (GUI), running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects.

Here's a small program called CreateObjectDemo that creates three objects: one Point object and two Rectangle objects. You will need all three source files to compile this program:

http://java.sun.com/docs/books/tutorial/java/data/ex5/CreateObjectDemo.java
http://java.sun.com/docs/books/tutorial/java/data/ex5/Point.java
http://java.sun.com/docs/books/tutorial/java/data/ex5/Rectangle.java
public class CreateObjectDemo {
    public static void main(String[] args) {
        // Declare and create a Point object 
        // and two Rectangle objects.
        Point originOne = new Point(23, 94);
        Rectangle rectOne = new Rectangle(originOne, 100, 200);
        Rectangle rectTwo = new Rectangle(50, 100);
        // Display rectOne's width, height, and area.
        System.out.println("Width of rectOne: " +
                rectOne.width);
        System.out.println("Height of rectOne: " +
                rectOne.height);
        System.out.println("Area of rectOne: " + rectOne.area());
        // Set rectTwo's position.
        rectTwo.origin = originOne;
        // Display rectTwo's position.
        System.out.println("X Position of rectTwo: "
                + rectTwo.origin.x);
        System.out.println("Y Position of rectTwo: "
        + rectTwo.origin.y);
        // Move rectTwo and display its new position.
        rectTwo.move(40, 72);
        System.out.println("X Position of rectTwo: "
                + rectTwo.origin.x);
        System.out.println("Y Position of rectTwo: "
                + rectTwo.origin.y);
    }
}    
This program creates, manipulates, and displays information about various objects. Here's the output:
    Width of rectOne: 100
    Height of rectOne: 200
    Area of rectOne: 20000
    X Position of rectTwo: 23
    Y Position of rectTwo: 94
    X Position of rectTwo: 40
    Y Position of rectTwo: 72
The following sections use the preceding example to describe the life cycle of an object within a program. From them, you will learn how to write code that creates and uses objects in your own programs. You will also learn how the system cleans up after an object after its life has ended.

Read the rest of this article.

What's New on Java Studio Creator
 
Using Page Fragments


About Page Fragments

A page fragment is a portion of a page, such as a header, footer, or navigation bar, that can be reused in other pages. For example, you might put a common element such as a graphic or a Search field in a page fragment and then include that fragment as a header in all pages in the application. You might also include your company name and copyright information in a page fragment and use that fragment as your application's footer. Like a main page, a page fragment is a JavaServer Pages (JSP) page with its own associated page bean; however, the file extension of a page fragment is jspf instead of jsp.

Designing a Page That Includes Page Fragments

You begin this tutorial by creating the home page for the application. You then create a header fragment and a navigation fragment and include these fragments in the home page.
  1. Create a new web application project and call it FragmentExample.

    Figure 1 shows the page that you will create in the following steps.

  2. From the Layout section of the Components Palette, drag a Page Fragment Box component onto the upper left corner of the page.

    The Select Page Fragment dialog box opens.

  3. Click Create New Page Fragment. Type CompanyLogo in the Name field and click OK.

    The page fragment appears on the page. In addition, the page fragment is added to the Projects window and also in a <div> block in the Outline window.

  4. Click Close to close the Select Page Fragment dialog box.

    The dotted line in the Visual Designer shows the size of the page fragment. The default size is 400 pixels wide by 200 pixels high.

  5. Place a second Page Fragment Box component on the left side of the page under the CompanyLogo page fragment. Name this page fragment Navigation.

  6. From the Basic section of the Palette, drag a Static Text component onto the page and drop it to the right of the Navigation page fragment. Be sure to drop the component on the page and not on the page fragment. Change the text of this component to Welcome to Sky Company.
Creating a Header Fragment

Now you define the content of the CompanyLogo fragment, as shown in Figure 2. Any changes you make to a fragment must be made in the fragment itself, not in the page.

Read the rest of this article.

Tutorials and Tips on NetBeans.org
 
Derby by Brian Leonard


Derby (Java DB) is the open-source database being developed as part of the Apache DB Project. The Derby project does not develop any GUI tooling. Derby support is included in NetBeans IDE 5.0 (starting with the RC1 release).

Get the Derby Database
  1. Download the latest official Derby release (10.1.2.1 at the time of this writing):
    http://db.apache.org/derby/derby_downloads.html
  2. Extract the archive.
  3. In the derby root directory (db-derby-10.1.2.1-bin), create a new folder, database.
Configure the Derby Database in the NetBeans IDE
  1. Select Tools > Options (NetBeans > Preferences on the Macintosh) and click the Advanced Options button. Expand the IDE Configuration > Server and External Tools Settings nodes and select the Derby Database node.
  2. Set the Derby Location to where you extracted the Derby archive (for example, D:\db-derby-10.1.2.1-bin).
  3. Set the Database Location to the location of the database folder created above (for example, D:\db-derby-10.1.2.1-bin\database) and close the Options dialog.


Start the Derby Server and Create a Database
  1. Select Tools > Derby Database > Start Derby Server. You'll see the following in the output window:



  2. Select Tools > Derby Database > Create Derby Database...
  3. Set the Database Name to Sample. Set the User Name and Password to nbuser.

  4. Switch to the Runtime tab (Ctrl + 5) and expand the Databases node to see your new database
Read the rest of the tutorial.

Sun's Java Technology Courses
 
Java Programming Language Workshop (VC-SL-285)


The Java Programming Language Workshop course provides students with practical experience in designing a vertical solution for a distributed, multitier application. Students use graphical user interface (GUI) design principles and network communications capabilities to code a functional Java application that interacts with a networked database server. The significant amount of lab time illustrates the workshop nature of this course.

This course is presented using Sun's web-based Live Virtual Class (LVC). The LVC is a dynamic and fully interactive online learning environment that features live teaching collaboration and instructor-assisted activities.

Learn more.

Program Challenge
 
Using Java SE 6, create a program that lists the available file system space for each root level file system.

Your program should look something like this:
http:


Free Developer Tools
 
Sun is offering the award-winning Sun Java Studio Enterprise and Sun Java Studio Creator IDEs at no cost to all developers worldwide who join Sun Developer Network (SDN).

Get your free tools.

For More Information
 
The terms "Java Virtual Machine" and "JVM" mean a Virtual Machine for the Java platform.


Downloading the Java Platform, Standard Edition (Java SE, formerly known as J2SE)
 
For most Java technology development, you need the class libraries, compiler, tools, and runtime environment provided with the Java SE development kit.

Download Java SE Platform

Bookmark the Specifications

New to Java Center


Rate and Review
Tell us what you think of the content of this page.
Excellent   Good   Fair   Poor  
Comments:
If you would like a reply to your comment, please submit your email address:
Note: We may not respond to all submitted comments.
Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: fundamentals_newsletter@sun.com

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.
  • Mobility Developer Newsletter. Learn about the latest releases, tools, and resources for developers working on wireless and Java Card technologies and applications.
  • Enterprise Java Technologies Newsletter. Learn about the latest in enterprise Java technology: releases, products, tools, resources, events, news, and views.
  • Core Java Technologies Tech Tips (formerly JDC Tech Tips). Get expert tips, sample code solutions, and techniques for developing in the Java Platform, Standard Edition (Java SE)
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 email 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

? 2006 Sun Microsystems, Inc. All Rights Reserved. For information on Sun's trademarks see: http://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.

To update your Sun subscription preferences or unsubscribe to Sun news services, click here or use this link https://softwarereg.sun.com/registration/developer/en_US/subscriptions



FEEDBACK

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

Sun Microsystems, Inc. 10 Network Circle, MPK10-209 Menlo Park, CA 94025 US