Write a program which generates random integers and stores them in a file named “rand.dat”. The program then reads the integers from the file and displays on the screen.
Code:
import java.io.*;
import java.util.*;
class S9P2_Random
{
public static void main(String args[])
{
FileWriter FW = null;
BufferedWriter bfwr = null;
File inFile = new File("rand.dat");
try
{
int rand_int;
FW = new FileWriter(inFile);
bfwr = new BufferedWriter(FW);
Random generate_rand = new Random();
System.out.println("\nGenerating & Storing Random integers from 0 to 99..\n");
for(int i=0; i<10; i++)
{
rand_int = generate_rand.nextInt(100);
System.out.print(rand_int+"\t");
bfwr.write(rand_int+"\r\n");
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
bfwr.close();
}
catch(IOException e){ }
}
try
{
System.out.println("\nRetrieving Random integers stored in file 'rand.dat'..");
Scanner scanner = new Scanner(inFile);
while(scanner.hasNextInt())
{
System.out.println(scanner.nextInt()+"\t");
}
}
catch(NullPointerException e)
{
System.out.println(e.getMessage());
}
catch(FileNotFoundException e)
{
System.out.println(e.getMessage());
}
}
}
Output: