You should only assume you'll be able to write to a file from an application. Although it may be possible to write data into a file from an applet if the browser viewing the applet is HotJava, this ability will generally be disabled. From within Netscape there is no way for an applet to write to a file on the local hard drive.

Within an application, however, file access is straight-forward. There are several ways but here is a simple example using formatted output streams:


class PrintToAFile  {

  public static void main (String args[]) {

    //First open the file you want to write into
    try {
      FileOutputStream fout =  new FileOutputStream("test.out");

      // now convert the FileOutputStream into a PrintStream

      PrintStream myOutput = new PrintStream(fout);

      // Now you're able to use println statements just as if you were using System.out.println
      // to write to the terminal 

      myOutput.println("Hello There!");
      myOutput.println(1 + " + " + 1 + " = " + (1+1));
    catch (IOException e) {
      System.out.println("Error opening file: " + e);

  } // main ends here


There are a number of other things to note about writing data to a file. This program creates or opens a file called "test.out" in the same directory as the running program. However you could pass it a full pathname to a file in a different directory instead.

You should also learn about the DataOutputStream class and the write() method when you get a chance. DataOutputStreams and DataInputStreams are used for moving data between Java programs in a portable way. The various incarnations of the write() method are used for writing and reading arbitrary byte streams. What I've demonstrated here is more suitable for human consumption.

In Java 1.1 you should probably use a PrintWriter instead of a PrintStream.

Posted in: Java

Related FAQ's

Marius Ion ANGEL HOT SOFT LLC (800) 316-7677