Printing Numbers to a Text File : Print To Files « File Input Output « Java






Printing Numbers to a Text File


import java.io.FileWriter;
import java.io.PrintWriter;

public class PrintWriterDemo {
  public static void main() throws Exception{
    PrintWriter pw = new PrintWriter(new FileWriter("dice.txt"));
    for (int i = 1; i <= 1000; i++) {
      int die = (int) (1 + 6 * Math.random());
      pw.print(die);
      pw.print(' ');
      if (i % 20 == 0)
        pw.println();
    }
    pw.println();
    pw.close(); // Without this, the output file may be empty
  }
}
           
       








Related examples in the same category

1.Printing an HTML Table
2.illustrates using a PrintWriter to handle console output