/* * Random data file */ package randomfile; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.Scanner; /** * * @author jcmtiernan */ public class RandomFile { public static void main(String[] args) throws IOException { final int COUNT_MAX = 100; final int RANGE_MAX = 1000; Scanner input = new Scanner(System.in); String dataFile = "matchdata1.dat"; File file = new File(dataFile); file = makeRandomPairFile(file, COUNT_MAX, RANGE_MAX); // creates test data file Scanner inputFile = new Scanner(file); System.out.println("Looping on COUNT_MAX, the data in the file is: "); for( int i = 0; i < COUNT_MAX; i++) { System.out.printf("%6d",inputFile.nextInt()); if ((i % 10)== 9) { System.out.printf("\n"); } } System.out.println("The data in the file was COUNT_MAX pairs so the loop only printed half. "); Scanner inputFile2 = new Scanner(file); System.out.println(); System.out.println(); int i = 0; System.out.println("Checking for whether there is more data, then all the data in the file is: "); while( inputFile2.hasNextInt()) { System.out.printf("%6d",inputFile2.nextInt()); if ((i++ % 10)== 9) { System.out.printf("\n"); } } } public static File makeRandomPairFile(File file, int max, int range) throws IOException { FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); int rand1, rand2; Random randGen = new Random(); //creating Random number generator for(int k = 0; k < max; k++) { rand1 = randGen.nextInt(range); // notice that two values are being printed rand2 = randGen.nextInt(range); bw.write(String.format("%8d%8d", rand1,rand2)); bw.newLine(); } bw.close();// be sure to close BufferedWriter return file; } }