Monday 13 March 2017

strictfp, Native Methods & Using assert - Java Tutorials

strictfp

Java 2 added a new keyword to the Java language, called strictfp. With the creation of Java 2, the floating point computation model was relaxed slightly to make certain floating point computations faster for certain processors, such as the Pentium. Specifically, the new model does not require the truncation of certain intermediate values that occur during a computation. By modifying a class or a method with strictfp, you ensure that floating point calculations (and thus all truncations) take place precisely as they did in earlier versions of Java. The truncation affects only the exponent of certain operations. When a class is modified by strictfp, all the methods in the class are also modified by strictfp automatically.

For example, the following fragment tells Java to use the original floating point model for calculations in all methods defined within MyClass:

strictfp class MyClass { //...

Frankly, most programmers never need to use strictfp, because it affects only a very small class of problems.




Native Methods

Although it is rare, occasionally, you may want to call a subroutine that is written in a language other than Java. Typically, such a subroutine exists as executable code for the CPU and environment in which you are working—that is, native code. For example, you may want to call a native code subroutine to achieve faster execution time. Or, you may want to use a specialized, third-party library, such as a statistical package.

However, because Java programs are compiled to bytecode, which is then interpreted (or compiled on-the-fly) by the Java run-time system, it would seem impossible to call a native code subroutine from within your Java program. Fortunately, this conclusion is false. Java provides the native keyword, which is used to declare native code methods. Once declared, these methods can be called from inside your Java program just as you call any other Java method.

To declare a native method, precede the method with the native modifier, but do not define any body for the method. For example:

  public native int meth() ;

After you declare a native method, you must write the native method and follow a rather complex series of steps to link it with your Java code.

Most native methods are written in C. The mechanism used to integrate C code with a Java program is called the Java Native Interface (JNI). This methodology was created by Java 1.1 and then expanded and enhanced by Java 2. (Java 1.0 used a different approach, which is now completely outdated.) A detailed description of the JNI is beyond the scope of this book, but the following description provides sufficient information for most applications.

The precise steps that you need to follow will vary between different Java environments and versions. This also depends on the language that you are using to implement the native method. The following discussion assumes a Windows 95/98/XP/NT/2000 environment. The language used to implement the native method is C.

The easiest way to understand the process is to work through an example. To begin, enter the following short program, which uses a native method called test( ):

  // A simple example that uses a native method.
  public class NativeDemo {
    int i;
    public static void main(String args[]) {
      NativeDemo ob = new NativeDemo();

      ob.i = 10;
      System.out.println("This is ob.i before the native method:" +
                          ob.i);
      ob.test(); // call a native method
      System.out.println("This is ob.i after the native method:" +
                          ob.i);
    }

    // declare native method
    public native void test() ;

    // load DLL that contains static method
    static {
      System.loadLibrary("NativeDemo");
    }
  }

Notice that the test( ) method is declared as native and has no body. This is the method that we will implement in C shortly. Also notice the static block. As explained earlier in this book, a static block is executed only once, when your program begins execution (or, more precisely, when its class is first loaded). In this case, it is used to load the dynamic link library that contains the native implementation of test( ). (You will see how to create this library soon.)

The library is loaded by the loadLibrary( ) method, which is part of the System class. This is its general form:

      static void loadLibrary(String filename)

Here, filename is a string that specifies the name of the file that holds the library. For the Windows environment, this file is assumed to have the .DLL extension.

After you enter the program, compile it to produce NativeDemo.class. Next, you must use javah.exe to produce one file: NativeDemo.h. (javah.exe is included in the SDK.) You will include NativeDemo.h in your implementation of test( ). To produce NativeDemo.h, use the following command:

      javah -jni NativeDemo

This command produces a header file called NativeDemo.h. This file must be included in the C file that implements test( ). The output produced by this command is shown here:

  /* DO NOT EDIT THIS FILE - it is machine generated */
  #include <jni.h>
  /* Header for class NativeDemo */

  #ifndef _Included_NativeDemo
  #define _Included_NativeDemo
  #ifdef _ _cplusplus
  extern "C" {
  #endif
  /*
   * Class: NativeDemo
   * Method: test
   * Signature: ()V
   */
  JNIEXPORT void JNICALL Java_NativeDemo_test
   (JNIEnv *, jobject);

  #ifdef _ _cplusplus
  }
  #endif
  #endif

Pay special attention to the following line, which defines the prototype for the test( ) function that you will create:

  JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *, jobject);

Notice that the name of the function is Java_NativeDemo_test( ). You must use this as the name of the native function that you implement. That is, instead of creating a C function called test( ), you will create one called Java_NativeDemo_test( ). The NativeDemo component of the prefix is added because it identifies the test( ) method as being part of the NativeDemo class. Remember, another class may define its own native test( ) method that is completely different from the one declared by NativeDemo. Including the class name in the prefix provides a way to differentiate between differing versions. As a general rule, native functions will be given a name whose prefix includes the name of the class in which they are declared.

After producing the necessary header file, you can write your implementation of test( ) and store it in a file named NativeDemo.c:

  /* This file contains the C version of the
     test() method.
  */

  #include <jni.h>
  #include "NativeDemo.h"
  #include <stdio.h>

  JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *env, jobject                                                 obj)
  {

    jclass cls;
    jfieldID fid;
    jint i;

    printf("Starting the native method.\n");
    cls = (*env)->GetObjectClass(env, obj);
    fid = (*env)->GetFieldID(env, cls, "i", "I");

    if(fid == 0) {
      printf("Could not get field id.\n");
      return;
    }
    i = (*env)->GetIntField(env, obj, fid);
    printf("i = %d\n", i);
    (*env)->SetIntField(env, obj, fid, 2*i);
    printf("Ending the native method.\n");
  }

Notice that this file includes jni.h, which contains interfacing information. This file is provided by your Java compiler. The header file NativeDemo.h was created by javah, earlier.

In this function, the GetObjectClass( ) method is used to obtain a C structure that has information about the class NativeDemo. The GetFieldID( ) method returns a C structure with information about the field named “i” for the class. GetIntField( ) retrieves the original value of that field. SetIntField( ) stores an updated value in that field. (See the file jni.h for additional methods that handle other types of data.)

After creating NativeDemo.c, you must compile it and create a DLL. To do this by using the Microsoft C/C++ compiler, use the following command line. (You might need to specifiy the path to jni.h and its subordinate file jni_md.h.)

      Cl /LD NativeDemo.c

This produces a file called NativeDemo.dll. Once this is done, you can execute the Java program, which will produce the following output:

  This is ob.i before the native method: 10
  Starting the native method.
  i = 10
  Ending the native method.
  This is ob.i after the native method: 20

The specifics surrounding the use of native are implementation- and environmentdependent. Furthermore, the specific manner in which you interface to Java code is subject to change. You must consult the documentation that accompanies your Java development system for details on native methods.


Problems with Native Methods

Native methods seem to offer great promise, because they enable you to gain access to your existing base of library routines, and they offer the possibility of faster run-time execution. But native methods also introduce two significant problems:
  • Potential security risk Because a native method executes actual machine code, it can gain access to any part of the host system. That is, native code is not confined to the Java execution environment. This could allow a virus infection, for example. For this reason, applets cannot use native methods. Also, the loading of DLLs can be restricted, and their loading is subject to the approval of the security manager.
  • Loss of portability Because the native code is contained in a DLL, it must be present on the machine that is executing the Java program. Further, because each native method is CPU- and operating-system-dependent, each DLL is inherently nonportable. Thus, a Java application that uses native methods will be able to run only on a machine for which a compatible DLL has been installed. The use of native methods should be restricted, because they render your Java programs nonportable and pose significant security risks.





Using assert

Java 2, version 1.4 added a new keyword to Java: assert. It is used during program development to create an assertion, which is a condition that should be true during the execution of the program. For example, you might have a method that should always return a positive integer value. You might test this by asserting that the return value is greater than zero using an assert statement. At run time, if the condition actually is true, no other action takes place. However, if the condition is false, then an AssertionError is thrown. Assertions are often used during testing to verify that some expected condition is actually met. They are not usually used for released code.

The assert keyword has two forms. The first is shown here.

      assert condition;

Here, condition is an expression that must evaluate to a Boolean result. If the result is true, then the assertion is true and no other action takes place. If the condition is false, then the assertion fails and a default AssertionError object is thrown. The second form of assert is shown here.

      assert condition : expr;

In this version, expr is a value that is passed to the AssertionError constructor. This value is converted to its string format and displayed if an assertion fails. Typically, you will specify a string for expr, but any non-void expression is allowed as long as it defines a reasonable string conversion.

Here is an example that uses assert. It verifies that the return value of getnum( ) is positive.

  // Demonstrate assert.
  class AssertDemo {
    static int val = 3;

    // Return an integer.
    static int getnum() {
      return val--;
    }

    public static void main(String args[])
    {
      int n;

      for(int i=0; i < 10; i++) {
        n = getnum();

        assert n > 0; // will fail when n is 0
        
        System.out.println("n is " + n);
      }
    }
  }

Programs that use assert must be compiled using the -source 1.4 option. For example, to compile the preceding program, use this line:

  javac -source 1.4 AssertDemo.java

To enable assertion checking at run time, you must specify the -ea option. For example, to enable assertions for AssertDemo, execute it using this line.

  java -ea AssertDemo

After compiling and running as just described, the program creates the following output.

  n is 3
  n is 2
  n is 1
  Exception in thread "main" java.lang.AssertionError
          at AssertDemo.main(AssertDemo.java:17)

In main( ), repeated calls are made to the method getnum( ), which returns an integer value. The return value of getnum( ) is assigned to n and then tested using this assert statement.

  assert n > 0; // will fail when n is 0

This statement will fail when n equals 0, which it will after the fourth call. When this happens, an exception is thrown.

As explained, you can specify the message displayed when an assertion fails. For example, if you substitute

  assert n > 0 : "n is negative!";

for the assertion in the preceding program, then the following ouptut will be generated.

 n is 3
 n is 2
 n is 1
 Exception in thread "main" java.lang.AssertionError: n is negative!
        at AssertDemo.main(AssertDemo.java:17)

One important point to understand about assertions is that you must not rely on them to perform any action actually required by the program. The reason is that normally, released code will be run with assertions disabled. For example, consider this variation of the preceding program.

  // A poor way to use assert!!!
  class AssertDemo {
    // get a random number generator
    static int val = 3;

    // Return an integer.
    static int getnum() {
      return val--;
    }

    public static void main(String args[])
    {
      int n = 0;

      for(int i=0; i < 10; i++) {

        assert (n = getnum()) > 0; // This is not a good idea!

        System.out.println("n is " + n);
      }
    }
  }

In this version of the program, the call to getnum( ) is moved inside the assert statement. Although this works fine if assertions are enabled, it will cause a malfunction when assertions are disabled because the call to getnum( ) will never be executed! In fact, n must now be initialized, because the compiler will recognize that it might not be assigned a value by the assert statement.

Assertions are a good addition to Java because they streamline the type of error checking that is common during development. For example, prior to assert, if you wanted to verify that n was positive in the preceding program, you had to use a sequence of code similar to this:

  if(n < 0) {
    System.out.println("n is negative!");
    return; // or throw an exception
  }

With assert, you need only one line of code. Furthermore, you don’t have to remove the assert statements from your released code.


Assertion Enabling and Disabling Options

When executing code, you can disable assertions by using the -da option. You can enable or disable a specific package by specifying its name after the -ea or -da option. For example, to enable assertions in a package called MyPack, use

  -ea:MyPack

To disable assertions in MyPack use

  -da:MyPack

To enable or disable all subpackages of a package, follow the package name with three dots. For example,

  -ea:MyPack...

You can also specify a class with the -ea or -da option. For example, this enables AssertDemo individually.

  -ea:AssertDemo

Applet Fundamentals, The transient and volatile Modifiers & Using instanceof - Java Tutorials

Applet Fundamentals

All of the preceding examples in this book have been Java applications. However, applications constitute only one class of Java programs. Another type of program is the applet. As mentioned in Chapter 1, applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a Web document. After an applet arrives on the client, it has limited access to resources, so that it can produce an arbitrary multimedia user interface and run complex computations without introducing the risk of viruses or breaching data integrity.

Many of the issues connected with the creation and use of applets are found in Part II, when the applet package is examined. However, the fundamentals connected to the creation of an applet are presented here, because applets are not structured in the same way as the programs that have been used thus far. As you will see, applets differ from applications in several key areas.

Let’s begin with the simple applet shown here:

  import java.awt.*;
  import java.applet.*;

  public class SimpleApplet extends Applet {
    public void paint(Graphics g) {
      g.drawString("A Simple Applet", 20, 20);
    }
  }

This applet begins with two import statements. The first imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user through the AWT, not through the console-based I/O classes. The AWT contains support for a window-based, graphical interface. As you might expect, the AWT is quite large and sophisticated, and a complete discussion of it consumes several chapters in Part II of this book. Fortunately, this simple applet makes very limited use of the AWT. The second import statement imports the applet package, which contains the class Applet. Every applet that you create must be a subclass of Applet.

The next line in the program declares the class SimpleApplet. This class must be declared as public, because it will be accessed by code that is outside the program.

Inside SimpleApplet, paint( ) is declared. This method is defined by the AWT and must be overridden by the applet. paint( ) is called each time that the applet must redisplay its output. This situation can occur for several reasons. For example, the window in which the applet is running can be overwritten by another window and then uncovered. Or, the applet window can be minimized and then restored. paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter contains the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required.

Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method outputs a string beginning at the specified X,Y location. It has the following general form:

      void drawString(String message, int x, int y)

Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is location 0,0. The call to drawString( ) in the applet causes the message “A Simple Applet” to be displayed beginning at location 20,20.

Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not begin execution at main( ). In fact, most applets don’t even have a main( ) method. Instead, an applet begins execution when the name of its class is passed to an applet viewer or to a network browser.

After you enter the source code for SimpleApplet, compile in the same way that you have been compiling programs. However, running SimpleApplet involves a different process. In fact, there are two ways in which you can run an applet:
  • Executing the applet within a Java-compatible Web browser.
  • Using an applet viewer, such as the standard SDK tool, appletviewer. An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test your applet.

Each of these methods is described next. To execute an applet in a Web browser, you need to write a short HTML text file that contains the appropriate APPLET tag. Here is the HTML file that executes
SimpleApplet:

  <applet code="SimpleApplet" width=200 height=60>
  </applet>

The width and height statements specify the dimensions of the display area used by the applet. (The APPLET tag contains several other options that are examined more closely in Part II.) After you create this file, you can execute your browser and then load this file, which causes SimpleApplet to be executed.

To execute SimpleApplet with an applet viewer, you may also execute the HTML file shown earlier. For example, if the preceding HTML file is called RunApp.html, then the following command line will run SimpleApplet:

      C:\>appletviewer RunApp.html

However, a more convenient method exists that you can use to speed up testing. Simply include a comment at the head of your Java source code file that contains the APPLET tag. By doing so, your code is documented with a prototype of the necessary HTML statements, and you can test your compiled applet merely by starting the applet viewer with your Java source code file. If you use this method, the SimpleApplet source file looks like this:

  import java.awt.*;
  import java.applet.*;
  /*
  <applet code="SimpleApplet" width=200 height=60>
  </applet>
  */

  public class SimpleApplet extends Applet {
    public void paint(Graphics g) {
      g.drawString("A Simple Applet", 20, 20);
    }
  }

In general, you can quickly iterate through applet development by using these three steps:
  1. Edit a Java source file.
  2. Compile your program.
  3. Execute the applet viewer, specifying the name of your applet’s source file. The applet viewer will encounter the APPLET tag within the comment and execute your applet.

While the subject of applets is more fully discussed later in this book, here are the key points that you should remember now:
  • Applets do not need a main( ) method.
  • Applets must be run under an applet viewer or a Java-compatible browser.
  • User I/O is not accomplished with Java’s stream I/O classes. Instead, applets use the interface provided by the AWT.





The transient and volatile Modifiers

Java defines two interesting type modifiers: transient and volatile. These modifiers are used to handle somewhat specialized situations. When an instance variable is declared as transient, then its value need not persist when an object is stored. For example:

  class T {
    transient int a; // will not persist
    int b; // will persist
  }

Here, if an object of type T is written to a persistent storage area, the contents of a would not be saved, but the contents of b would.

The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program. One of these situations involves multithreaded programs. (You saw an example of this in Chapter 11.) In a multithreaded program, sometimes, two or more threads share the same instance variable. For efficiency considerations, each thread can keep its own, private copy of such a shared variable. The real (or master) copy of the variable is updated at various times, such as when a synchronized method is entered. While this approach works fine, it may be inefficient at times. In some cases, all that really matters is that the master copy of a variable always reflects its current state. To ensure this, simply specify the variable as volatile, which tells the compiler that it must always use the master copy of a volatile variable (or, at least, always keep any private copies up to date with the master copy, and vice versa). Also, accesses to the master variable must be executed in the precise order in which they are executed on any private copy.

volatile in Java has, more or less, the same meaning that it has in C/C++/C#.




Using instanceof

Sometimes, knowing the type of an object during run time is useful. For example, you might have one thread of execution that generates various types of objects, and another thread that processes these objects. In this situation, it might be useful for the processing thread to know the type of each object when it receives it. Another situation in which knowledge of an object’s type at run time is important involves casting. In Java, an invalid cast causes a run-time error. Many invalid casts can be caught at compile time. However, casts involving class hierarchies can produce invalid casts that can be detected only at run time. For example, a superclass called A can produce two subclasses, called B
and C. Thus, casting a B object into type A or casting a C object into type A is legal, but casting a B object into type C (or vice versa) isn’t legal. Because an object of type A can refer to objects of either B or C, how can you know, at run time, what type of object is actually being referred to before attempting the cast to type C? It could be an object of type A, B, or C. If it is an object of type B, a run-time exception will be thrown. Java provides the run-time operator instanceof to answer this question.

The instanceof operator has this general form:

      object instanceof type

Here, object is an instance of a class, and type is a class type. If object is of the specified type or can be cast into the specified type, then the instanceof operator evaluates to true. Otherwise, its result is false. Thus, instanceof is the means by which your program can obtain run-time type information about an object.

The following program demonstrates instanceof:

  // Demonstrate instanceof operator.
  class A {
    int i, j;
  }

  class B {
    int i, j;
  }

  class C extends A {
    int k;
  }

  class D extends A {
    int k;
  }
  
  class InstanceOf {
    public static void main(String args[]) {
      A a = new A();
      B b = new B();
      C c = new C();
      D d = new D();

      if(a instanceof A)
        System.out.println("a is instance of A");
      if(b instanceof B)
        System.out.println("b is instance of B");
      if(c instanceof C)
        System.out.println("c is instance of C");
      if(c instanceof A)
        System.out.println("c can be cast to A");

      if(a instanceof C)
        System.out.println("a can be cast to C");

      System.out.println();
      
      // compare types of derived types
      A ob;

      ob = d; // A reference to d
      System.out.println("ob now refers to d");
      if(ob instanceof D)
        System.out.println("ob is instance of D");

      System.out.println();

      ob = c; // A reference to c
      System.out.println("ob now refers to c");

      if(ob instanceof D)
        System.out.println("ob can be cast to D");
      else
        System.out.println("ob cannot be cast to D");

      if(ob instanceof A)
        System.out.println("ob can be cast to A");

      System.out.println();

      // all objects can be cast to Object
      if(a instanceof Object)
        System.out.println("a may be cast to Object");
      if(b instanceof Object)
        System.out.println("b may be cast to Object");
      if(c instanceof Object)
        System.out.println("c may be cast to Object");
      if(d instanceof Object)
        System.out.println("d may be cast to Object");
    }
  }

The output from this program is shown here:

  a is instance of A
  b is instance of B
  c is instance of C
  c can be cast to A
  ob now refers to d
  ob is instance of D

  ob now refers to c
  ob cannot be cast to D
  ob can be cast to A

  a may be cast to Object
  b may be cast to Object
  c may be cast to Object
  d may be cast to Object

The instanceof operator isn’t needed by most programs, because, generally, you know the type of object with which you are working. However, it can be very useful when you’re writing generalized routines that operate on objects of a complex class hierarchy.

Writing Console Output, The PrintWriter Class & Reading and Writing Files - Java Tutorials

Writing Console Output

Console output is most easily accomplished with print( ) and println( ), described earlier, which are used in most of the examples in this book. These methods are defined by the class PrintStream (which is the type of the object referenced by System.out). Even though System.out is a byte stream, using it for simple program output is still acceptable. However, a character-based alternative is described in the next section.

Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is shown here:

      void write(int byteval)

This method writes to the stream the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written. Here is a short example that uses write( ) to output the character “A” followed by a newline to the screen:

  // Demonstrate System.out.write().
  class WriteDemo {
    public static void main(String args[]) {
      int b;

      b = 'A';
      System.out.write(b);
      System.out.write('\n');
    }
  }

You will not often use write( ) to perform console output (although doing so might be useful in some situations), because print( ) and println( ) are substantially easier to use.




The PrintWriter Class

Although using System.out to write to the console is still permissible under Java, its use is recommended mostly for debugging purposes or for sample programs, such as those found in this book. For real-world programs, the recommended method of writing to the console when using Java is through a PrintWriter stream. PrintWriter is one of the character-based classes. Using a character-based class for console output makes it easier to internationalize your program.

PrintWriter defines several constructors. The one we will use is shown here:

      PrintWriter(OutputStream outputStream, boolean flushOnNewline)

Here, outputStream is an object of type OutputStream, and flushOnNewline controls whether Java flushes the output stream every time a println( ) method is called. If flushOnNewline is true, flushing automatically takes place. If false, flushing is not automatic.

PrintWriter supports the print( ) and println( ) methods for all types including Object. Thus, you can use these methods in the same way as they have been used with System.out. If an argument is not a simple type, the PrintWriter methods call the object’s toString( ) method and then print the result.

To write to the console by using a PrintWriter, specify System.out for the output stream and flush the stream after each newline. For example, this line of code creates a PrintWriter that is connected to console output:

  PrintWriter pw = new PrintWriter(System.out, true);

The following application illustrates using a PrintWriter to handle console output:

  // Demonstrate PrintWriter
  import java.io.*;

  public class PrintWriterDemo {
    public static void main(String args[]) {
      PrintWriter pw = new PrintWriter(System.out, true);
      pw.println("This is a string");
      int i = -7;
      pw.println(i);
      double d = 4.5e-7;
      pw.println(d);
    }
  }

The output from this program is shown here:

  This is a string
  -7
  4.5E-7

Remember, there is nothing wrong with using System.out to write simple text output to the console when you are learning Java or debugging your programs. However, using a PrintWriter will make your real-world applications easier to internationalize. Because no advantage is gained by using a PrintWriter in the sample programs shown in this book, we will continue to use System.out to write to the console.




Reading and Writing Files

Java provides a number of classes and methods that allow you to read and write files. In Java, all files are byte-oriented, and Java provides methods to read and write bytes from and to a file. However, Java allows you to wrap a byte-oriented file stream within a character-based object. This technique is described in Part II. This chapter examines the basics of file I/O.

Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files. To open a file, you simply create an object of one of these classes, specifying the name of the file as an argument to the constructor. While both classes support additional, overridden constructors, the following are the forms that we will be using:

      FileInputStream(String fileName) throws FileNotFoundException
      FileOutputStream(String fileName) throws FileNotFoundException

Here, fileName specifies the name of the file that you want to open. When you create an input stream, if the file does not exist, then FileNotFoundException is thrown. For output streams, if the file cannot be created, then FileNotFoundException is thrown. When an output file is opened, any preexisting file by the same name is destroyed.

In earlier versions of Java, FileOutputStream( ) threw an IOException when an output file could not be created. This was changed by Java 2.

When you are done with a file, you should close it by calling close( ). It is defined by both FileInputStream and FileOutputStream, as shown here:

      void close( ) throws IOException

To read from a file, you can use a version of read( ) that is defined within FileInputStream. The one that we will use is shown here:

      int read( ) throws IOException

Each time that it is called, it reads a single byte from the file and returns the byte as an integer value. read( ) returns –1 when the end of the file is encountered. It can throw an IOException.

The following program uses read( ) to input and display the contents of a text file, the name of which is specified as a command-line argument. Note the try/catch blocks that handle the two errors that might occur when this program is used—the specified file not being found or the user forgetting to include the name of the file. You can use this same approach whenever you use command-line arguments.

  /* Display a text file.

     To use this program, specify the name
     of the file that you want to see.
     For example, to see a file called TEST.TXT,
     use the following command line.

     java ShowFile TEST.TXT
  */

  import java.io.*;

  class ShowFile {
    public static void main(String args[])
      throws IOException
    {
      int i;
      FileInputStream fin;

      try {
        fin = new FileInputStream(args[0]);
      } catch(FileNotFoundException e) {
        System.out.println("File Not Found");
        return;
      } catch(ArrayIndexOutOfBoundsException e) {
        System.out.println("Usage: ShowFile File");
        return;
      }

      // read characters until EOF is encountered
      do {
        i = fin.read();
        if(i != -1) System.out.print((char) i);
      } while(i != -1);
      fin.close();
    }
  }

To write to a file, you will use the write( ) method defined by FileOutputStream. Its simplest form is shown here:

      void write(int byteval) throws IOException

This method writes the byte specified by byteval to the file. Although byteval is declared as an integer, only the low-order eight bits are written to the file. If an error occurs during writing, an IOException is thrown. The next example uses write( ) to copy a text file:

  /* Copy a text file.
     
     To use this program, specify the name
     of the source file and the destination file.
     For example, to copy a file called FIRST.TXT
     to a file called SECOND.TXT, use the following
     command line.
     
     java CopyFile FIRST.TXT SECOND.TXT
  */

  import java.io.*;
  
  class CopyFile {
    public static void main(String args[])
      throws IOException
    {
      int i;
      FileInputStream fin;
      FileOutputStream fout;

      try {
        // open input file
        try {
          fin = new FileInputStream(args[0]);
        } catch(FileNotFoundException e) {
          System.out.println("Input File Not Found");
          return;
        }

        // open output file
        try {
          fout = new FileOutputStream(args[1]);
        } catch(FileNotFoundException e) {
          System.out.println("Error Opening Output File");
          return;
        }
      } catch(ArrayIndexOutOfBoundsException e) {
        System.out.println("Usage: CopyFile From To");
        return;
      }

      // Copy File
      try {
        do {
          i = fin.read();
          if(i != -1) fout.write(i);
        } while(i != -1);
      } catch(IOException e) {
        System.out.println("File Error");
      }
        
      fin.close()
      fout.close();
    }
  }

Notice the way that potential I/O errors are handled in this program and in the preceding ShowFile program. Unlike some other computer languages, including C and C++, which use error codes to report file errors, Java uses its exception handling mechanism. Not only does this make file handling cleaner, but it also enables Java to easily differentiate the end-of-file condition from file errors when input is being performed. In C/C++, many input functions return the same value when an error occurs and when the end of the file is reached. (That is, in C/C++, an EOF condition often is mapped to the same value as an input error.) This usually means that the programmer must include extra program statements to determine which event actually occurred. In Java, errors are passed to your program via exceptions, not by values returned by read( ). Thus, when read( ) returns –1, it means only one thing: the end of the file has been encountered.