Java Technology Home Page
A-Z Index

Java Developer Connection(SM)
Technical Tips

Downloads, APIs, Documentation
Java Developer Connection
Tutorials, Tech Articles, Training
Online Support
Community Discussion
News & Events from Everywhere
Products from Everywhere
How Java Technology is Used Worldwide
Print Button
 
Tech Tips index

Tech Tips
May 21, 1998

This issue presents tips, techniques, and sample code for the following topics:

Temporary Files
In programming applications you often need to use temporary files -- files that are created during program execution to hold transient information. A typical case is a language compiler that uses several passes (such as preprocessing or assembly) with temporary files used to hold the output of the previous pass. In some cases, you could use memory instead of disk files, but you can't always assume that the required amount of memory will be available.

One feature in JDKTM 1.2 is the ability to create temporary files. These files are created in a specified directory or in the default system temporary directory (such as C:\TEMP on Windows systems). The temporary name is something like the following:

	t:\tmp\tmp-21885.tmp

The same name is not returned twice during the lifetime of the Java1 virtual machine. The returned temporary file is in a File object and can be used like any other file. Note: With Unix, you may find that your input file has to also reside in the same file system where the temporary files are stored. The renameTo method cannot rename files across file systems.

Here is an example of using temporary files to convert an input file to upper case:

import java.io.*;
   
public class upper {
  public static void main(String args[])
  {
// check command-line argument
   
    if (args.length != 1) {
      System.err.println("usage: upper file");
      System.exit(1);
    }
    String in_file = args[0];
   
    try {
// create temporary and mark "delete on exit"
   
      File tmpf = File.createTempFile("tmp");
      tmpf.deleteOnExit();
      System.err.println("temp file = " + tmpf);
   
// copy to temporary file,
// converting to upper case
   
      File inf = new File(in_file);
      FileReader fr = new FileReader(in_file);
      BufferedReader br = new BufferedReader(fr);
      FileWriter fw =
        new FileWriter(tmpf.getPath());
      BufferedWriter bw =
        new BufferedWriter(fw);
      String s = null;
      while ((s = br.readLine()) != null) {
        s = s.toUpperCase();
        bw.write(s, 0, s.length());
        bw.newLine();
      }
      br.close();
      bw.close();
   
// rename temporary file back to original file
   
      if (!inf.delete() || !tmpf.renameTo(inf))
        System.err.println("rename failed");
    }
    catch (IOException e) {
      System.err.println(e);
    }
  }
}

The input file is copied to the temporary file, and the file contents are converted to upper case. The temporary file is then renamed back to the input file.

JDK 1.2 also provides a mechanism whereby files can be marked for "delete on exit." That is, when the Java virtual machine exits, the file is deleted. An aspect worth noting in the above program is that this feature handles the case where the temporary file is created, and then an error occurs (for example, the input file does not exist). The delete-on-exit feature guarantees that the temporary file is deleted in the case of abnormal program termination.

Resource Bundles
One of the strengths of the Java programming language is the variety of language and API mechanisms that promote internationalization. For example, Unicode characters (16 bits) support more character sets than the typical 8-bit character set used in other languages.

One of the most important of these mechanisms is known as "resource bundles." A resource bundle contains locale-specific objects, for example strings representing messages to be displayed in your application. The idea is to load a specific bundle of resources, based on a particular locale.

To show how this mechanism works, here's a short example that retrieves and displays the phrase for "good morning" in two different languages:

  # German greeting file (greet_de.properties)

  morn=Guten Morgen

  # English greeting file (greet_en.properties)

  morn=Good morning

The above lines make up two text files, greet_de.properties and greet_en.properties. These are simple resource bundles.

The following program accesses the resource bundles:

import java.util.*;
   
public class bundle {
  public static String getGreet(String f, 
                         String key, Locale lc)
  {
    String s = null;
    try {
      ResourceBundle rb =
        ResourceBundle.getBundle(f, lc);
      s = rb.getString(key);
    }
    catch (MissingResourceException e) {
      s = null;
    }
    return s;
  }
   
  public static void main(String args[])
  {
    String fn = "greet";
    String mornkey = "morn";
    Locale ger = Locale.GERMAN;
    Locale eng = Locale.ENGLISH;
   
    System.out.println("German locale = " + ger);
    System.out.println("English locale = " + eng);
   
    System.out.println(getGreet(fn, mornkey, ger));
    System.out.println(getGreet(fn, mornkey, eng));
  }
}

The idea is that ResourceBundle.getBundle looks up a particular bundle, based on the locale name ("de" or "en"). The bundles in this example are property files (see java.util.Properties), with "key=value" pairs in them, and the files are located in the current directory. A particular bundle is retrieved based on the locale, and then a specific key is looked up, and the corresponding value returned. Note that there are a number of additional aspects to resource bundle naming and lookup that you should acquaint yourself with if you're concerned with internationalization issues. Resource bundles are commonly used to represent a collection of message strings, but other types of entities, such as icons, can also be stored in bundles.

The output of the program is:

   German locale = de
   English locale = en
   Guten Morgen
   Good morning

Finally, if you program your application's message display features in terms of locales and resource bundles, as this example illustrates, then you have taken an important step toward internationalizing your program.

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


Print Button
[ This page was updated: 21-Sep-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary | Feedback | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Sun Microsystems, Inc.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.