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