Files

Creating an Output File

Instead of showing the table in the console window, the program below writes the output to a file.

CODE
Compare this program to the previous one:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package inchestable;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class InchesTable {
  public static void printTable(BufferedWriter bw) throws IOException {
    bw.write("Inches   CM");
    bw.newLine();
    for(int inches=1; inches<20; inches++) {
      bw.write(String.format("%2d     %.2f%n",inches, inches*2.54));
    }//for
  }//printTable
  public static int openFile()throws IOException {
    try {
      File helloFile = new File("c:/myData/inches.txt");
      if (!helloFile.exists()) {
         helloFile.createNewFile();
      } //doesn't exist create it, otherwise overwrite it
      FileWriter fw = new FileWriter(helloFile.getAbsoluteFile());
      BufferedWriter bw = new BufferedWriter(fw);
      printTable(bw);
      bw.close();
      return 1;//success
    } //try
    catch (IOException e) { 
	return 0; //failure
    }	//catch
  }//openFile
  public static void main(String[] args) throws IOException {
      int result=openFile();
      if(result==0)System.out.println("File could not be created");
      else System.out.println("File created successfully");
  }//main
}//class
CODE

The output file will look like this: file.

NEXT: