|
| 1 | +package ch_22; |
| 2 | + |
| 3 | +import ch_22.exercise22_08.Exercise22_08; |
| 4 | + |
| 5 | +import java.io.File; |
| 6 | +import java.io.IOException; |
| 7 | +import java.io.RandomAccessFile; |
| 8 | +import java.util.Arrays; |
| 9 | + |
| 10 | +/** |
| 11 | + * 22.12 (Last 100 prime numbers) Programming Exercise 22.8 stores the prime numbers |
| 12 | + * in a file named PrimeNumbers.dat. |
| 13 | + * Write an efficient program that reads |
| 14 | + * the last 100 numbers in the file. (Hint: Don’t read all numbers from the file. |
| 15 | + * Skip all numbers before the last 100 numbers in the file.) |
| 16 | + * <p> |
| 17 | + */ |
| 18 | +public class Exercise22_12 { |
| 19 | + private static final String[] packageParts = Exercise22_08.class.getPackage().getName().split("\\."); |
| 20 | + private static final String PATH = packageParts[0] + File.separator + packageParts[1] + File.separator + "PrimeNumbers.dat"; |
| 21 | + private static final long UPPER_BOUND = 10_000_000_000L; |
| 22 | + private static final long BYTE_PER_LONG = 8; |
| 23 | + |
| 24 | + public static void main(String[] args) throws Exception { |
| 25 | + File dataFile = new File(PATH); |
| 26 | + boolean createdOrExists = dataFile.exists(); |
| 27 | + /* If file does not exist, this is the first run, starting from first prime number */ |
| 28 | + if (!createdOrExists) { |
| 29 | + System.out.println("Prime Storage File from Exercise 22 08 does not exist. Please run Exercise 22 08 first."); |
| 30 | + System.exit(0); |
| 31 | + } else { |
| 32 | + /* Need file channel to be: Closable, seekable, readable, writable */ |
| 33 | + try (RandomAccessFile randomAccessFile = new RandomAccessFile(dataFile, "rws")) { |
| 34 | + long[] last100Primes = new long[100]; |
| 35 | + long endOfFilePointer = randomAccessFile.length(); // Get pointer to end of the last byte in the file |
| 36 | + /* Calc pointer to start point for reading the last 100 numbers in the file */ |
| 37 | + long bytePointer = endOfFilePointer - (BYTE_PER_LONG * 100); // bytes per long * 100 numbers from end |
| 38 | + randomAccessFile.seek(bytePointer); |
| 39 | + int readCount = 0; |
| 40 | + long nextPrime = 0; |
| 41 | + while (nextPrime < UPPER_BOUND && readCount < 100) { |
| 42 | + nextPrime = randomAccessFile.readLong(); |
| 43 | + last100Primes[readCount] = nextPrime; |
| 44 | + readCount++; |
| 45 | + } |
| 46 | + System.out.println("Last 100 primes in the file: "); |
| 47 | + System.out.println("================================"); |
| 48 | + System.out.println(Arrays.toString(last100Primes)); |
| 49 | + |
| 50 | + } catch (IOException ioException) { |
| 51 | + throw new Exception("IOException while creating in and out file stream: \n" + ioException.getMessage()); |
| 52 | + } |
| 53 | + |
| 54 | + |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments