Free Java Guide










These tutorials will introduce you to Java programming Language. You'll compile and run your own Java application, using Sun's JDK. It's extremely easy to learn java programming skills, and in these parts, you'll learn how to write, compile, and run Java applications. Before you can develop corejava applications, you'll need to download the Java Development Kit (JDK).


PART-5


File I/O and Streams

You can write data to a file instead of the computer screen. You can write certain data to a file while still putting other data on the screen. Or you may need access to multiple files simultaneously. Or you may want to query the user for input rather than accepting it all on the command line. Or maybe you want to read data out of a file that's in a particular format. In Java all these methods take place as streams. < > Using File I/O streams. The System.out.println() statement we've been using all along is an implementation of Streams.

A program that writes a string to a file

In order to use the Java file classes, we must import the Java input/output package (java.io) in the following manner

import java.io.*;

Inside the main method of our program, we must declare a FileOutputStream object. In this case, we wish to write a string to the file, and so we create a new PrintStream object that takes as its constructor the existing FileOutputStream. Any data we send from PrintStream will now be passed to the FileOutputStream, and ultimately to disk. We then make a call to the println method, passing it a string, and then close the connection.

Source Code

/*
* FileOutput
* Demonstration of FileOutputStream and PrintStream classes
*/

import java.io.*;

class FileOutput 


public static void main(String args[])

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try
{
// Create a new file output stream connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");

// Connect print stream to the output stream
p = new PrintStream( out );

p.println ("This is written to a file myFile.txt");

p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to the file myFile.txt");
}
}
}

Interactively communicating with the user

Program asking  the user for their name and then prints a personalized greeting.

Source Code

import java.io.*;

class PersonalHello {

  public static void main (String args[])
    {
    
      byte name[] = new byte[100];
      int nr_read = 0;

      System.out.println("Your name Please?");
      try {
        nr_read = System.in.read(name);
        System.out.print("Hello ");
        System.out.write(name,0,nr_read);
      }
      catch (IOException e) {
        System.out.print("I did not get your name.");
      }
      
    }
    
}

In code that does any significant input or output you'll want to begin by importing all the various java.io classes. import.java.io.*; Most of the reading and writing you do in Java will be done with bytes. Here we've started with an array of bytes that will hold the user's name.

First we print a query requesting the user's name. Then we read the user's name using the System.in.read() method. This method takes a byte array as an argument, and places whatever the user types in that byte array. Then, like before, we print "Hello." Finally we print the user's name.

The program doesn't actually see what the user types until he or she types a carriage return. This gives the user the chance to backspace over and delete any mistakes. Once the return key is pressed, everything in the line is placed in the array.

Reading Numbers

Often strings aren't enough. A lot of times you'll want to ask the user for a number as input. All user input comes in as strings so we need to convert the string into a number.

The getNextInteger() method that will accept an integer from the user. Here it is:

  static int getNextInteger() {
  
    String line;
  
    DataInputStream in = new DataInputStream(System.in);
    try {
      line = in.readLine();
      int i = Integer.valueOf(line).intValue();
      return i;
    }
    catch (Exception e) {
      return -1;
    }
       
  } // getNextInteger ends here

Reading Formatted Data

It's often the case that you want to read not just one number but multiple numbers. Sometimes you may need to read text and numbers on the same line. For this purpose Java provides the StreamTokenizer class.

Writing a text file

Sometimes you want to save your output in a  file. To do this we'll need to learn how to write data to a file. 

Source Code

// Write the Fahrenheit to Celsius table in a file

import java.io.*;

class FahrToCelsius  {

  public static void main (String args[]) {

    double fahr, celsius;
    double lower, upper, step;

    lower = 0.0;    // lower limit of temperature table
    upper = 300.0;  // upper limit of temperature table
    step  = 20.0;   // step size

    fahr = lower;
  
    try {

      FileOutputStream fout =  new FileOutputStream("test.out");

      // now to the FileOutputStream into a PrintStream
      PrintStream myOutput = new PrintStream(fout);
  
      while (fahr <= upper) {  // while loop begins here
        celsius = 5.0 * (fahr-32.0) / 9.0;
        myOutput.println(fahr + " " + celsius);
        fahr = fahr + step;
      } // while loop ends here
  
    }  // try ends here
    catch (IOException e) {
      System.out.println("Error: " + e);
      System.exit(1);
    }
  
  } // main ends here

}

There are only three things necessary to write formatted output to a file rather than to the standard output:
  1. Open a FileOutputStream using a line like

    FileOutputStream fout =  new FileOutputStream("test.out");

    This line initializes the FileOutputStream with the name of the file you want to write into.
  2. Convert the FileOutputStream into a PrintStream using a statement like

    PrintStream myOutput = new PrintStream(fout);

    The PrintStream is passed the FileOutputStream from step 1.

  3. Instead of using System.out.println() use myOutput.println(). System.out and myOutput are just different instances of the PrintStream class. To print to a different PrintStream we keep the syntax the same but change the name of the PrintStream.

Reading a text file

Now that we know how to write a text file, let's try reading one. The following code accepts a series of file names on the command line and then prints those filenames to the standard output in the order they were listed.

// Imitate the Unix cat utility

import java.io.*;

class cat  {

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

  //Loop across the arguments
  for (int i=0; i < args.length; i++) {
 
  //Open the file for reading
  try {
    FileInputStream fin =  new FileInputStream(args[i]);

    // now turn the FileInputStream into a DataInputStream
    try {
      DataInputStream myInput = new DataInputStream(fin);
  
      try {
        while ((thisLine = myInput.readLine()) != null) {  // while loop begins here
          System.out.println(thisLine);
        } // while loop ends here
      }
      catch (Exception e) {
       System.out.println("Error: " + e);
      }
    } // end try
    catch (Exception e) {
      System.out.println("Error: " + e);
    }
  
   } // end try
   catch (Exception e) {
    System.out.println("failed to open file " + args[i]);
    System.out.println("Error: " + e);
  }
  } // for end here
  
  } // main ends here

}