Creating Java Code that Messes with Your Hard Drive

By Barry A. Burd

Experienced Java programmers have seen code that messes with your hard drive. But, what should you do with it? Let’s take a look.

“I _____ (print your name)_____ agree to pay $______each month on the ___th day of the month.”

Fill in the blanks. That’s all you have to do. Reading input from a disk can work the same way. Just fill in the blanks in the code below.

/*

* Before Eclipse can compile this code,

* you must fill in the blanks.

*/

import java.util.Scanner;

import java.io.File;

import java.io.FileNotFoundException;

 

class ___________ {

 

public static void main(String args[])throws FileNotFoundException {

 

Scanner diskScanner = new Scanner(new File("_________"));

 

______ = diskScanner.nextInt();

______ = diskScanner.nextDouble();

______ = diskScanner.nextLine();

______ = diskScanner.findWithinHorizon(".",0).charAt(0);

 

// Etc.

 

diskScanner.close();

}

}

To use this code, make up a name for your class. Insert that name into the first blank space. Type the name of the input file in the second space (between the quotation marks). Then, to read a whole number from the input file, call diskScanner.nextInt. To read a number that has a decimal point, call diskScanner.nextDouble. You can call any of the Scanner methods.

The stuff above isn’t a complete program. Instead, it’s a code template — a half-baked piece of code, with spaces for you to fill in.

With the template in the code above, you can input data from a disk file. With a similar template, you can write output to a file. The template is in the code below.

/*

* Before Eclipse can compile this code,

* you must fill in the blanks.

*/

import java.io.File;

import java.io.FileNotFoundException;

import java.io.PrintStream;

 

class ___________ {

 

public static void main(String args[])throws FileNotFoundException {

 

PrintStream diskWriter = new PrintStream("_________");

 

diskWriter.print(_____);

diskWriter.println(_____);

 

// Etc.

 

diskWriter.close();

}

}

To use this code, insert the name of your class into the first blank space. Type the name of the output file in the space between the quotation marks. Then, to write part of a line to the output file, call diskWriter.print. To write the remainder of a line to the output file, call diskWriter.println.

Eclipse has a built-in feature for creating and inserting code templates. To get started using Eclipse templates, choose Window → Preferences (in Windows) or Eclipse → Preferences (on a Mac). In the resulting Preferences dialog box, choose Java → Editor → Templates. Creating new templates isn’t simple. But if you poke around a bit, you accomplish a lot.

If your program gets input from one disk file and writes output to another, combine the stuff from both sets of code above.