public class BinaryFileOperations
1: import java.io.DataOutputStream;
2: import java.io.FileNotFoundException;
3: import java.io.FileOutputStream;
4: import java.io.IOException;
5: import java.util.Random;
7: /**
8: A class of methods that create a binary file of
9: random integers.
10:
11: @author Frank M. Carrano
12: @author Timothy M. Henry
13: @version 5.0
14: */
15: public class BinaryFileOperations
16: {
17: /** Writes a given number of random integers to the named binary file.
18: @param fileName The file name as a string.
19: @param howMany The positive number of integers to be written.
20: @return An integer code indicating the outcome of the operation:
21: 0 = Success; > 0 = Error opening (1), writing (2), or closing (3)
22: the file. */
23: public static int createRandomIntegerFile(String fileName, int howMany)
24: {
25: int resultCode = 0;
26: Random generator = new Random();
27: DataOutputStream toFile = null;
28: try
29: {
30: FileOutputStream fos = new FileOutputStream(fileName);
31: toFile = new DataOutputStream(fos);
32:
33: for (int counter = 0; counter < howMany; counter++)
34: {
35: toFile.writeInt(generator.nextInt());
36: } // end for
37: }
38: catch (FileNotFoundException e)
39: {
40: resultCode = 1; // Error opening file
41: }
42: catch (IOException e)
43: {
44: resultCode = 2; // Error writing file
45: }
46: finally
47: {
48: try
49: {
50: if (toFile != null)
51: toFile.close();
52: }
53: catch (IOException e)
54: {
55: resultCode = 3; // Error closing file
56: }
57:
58: return resultCode;
59: }
60: } // end createRandomIntegerFile
61: } // end BinaryFileOperations