-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathPrimeStorage.java
96 lines (81 loc) · 3.15 KB
/
PrimeStorage.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package ch_22.exercise22_08;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class PrimeStorage {
protected File dataFile;
private boolean firstRun;
private long nextNumberToCheck = 0;
private RandomAccessFile randomAccessFile;
public PrimeStorage(String storageFilePath) throws Exception {
dataFile = new File(storageFilePath);
boolean createdOrExists = dataFile.exists();
/* If file does not exist, this is the first run, starting from first prime number */
if (!createdOrExists) {
this.firstRun = true;
try {
createdOrExists = dataFile.createNewFile();
} catch (IOException ioe) {
throw new Exception("Error while trying to create storage file: " + ioe.getLocalizedMessage());
}
}
if (createdOrExists) {
/* Need file channel to be: Closable, seekable, readable, writable */
try {
randomAccessFile = new RandomAccessFile(dataFile, "rws");
// Handle different startup flows
if (firstRun) {
nextNumberToCheck = initializePrimes();
} else {
nextNumberToCheck = restartPrimes();
}
} catch (IOException ioException) {
throw new Exception("IOException while creating in and out file stream: \n" + ioException.getMessage());
}
}
}
private long restartPrimes() throws IOException {
long totalBytes = randomAccessFile.length();
randomAccessFile.seek(totalBytes - 8); // Seek to read the last 8 bytes in the file
long lastPrime = randomAccessFile.readLong();
return nextNumberToCheck = lastPrime + 1;
}
private long initializePrimes() throws IOException {
/* First time running program, prep the file by writing first two prime numbers */
randomAccessFile.writeLong(2L);
randomAccessFile.writeLong(3L);
return 4;
}
public long[] readNextPrimes() {
long[] primes = new long[10000];
try {
for (int i = 0; i < primes.length && (randomAccessFile.getFilePointer() < randomAccessFile.length()); i++) {
primes[i] = randomAccessFile.readLong();
}
} catch (EOFException eof) {
System.out.println("End of File Reached");
return primes;
} catch (IOException e) {
e.printStackTrace();
}
return primes;
}
public void appendPrime(long primeNumber) throws IOException {
long totalBytes = randomAccessFile.length();
randomAccessFile.seek(totalBytes);
randomAccessFile.writeLong(primeNumber);
}
public boolean isFirstRun() {
return firstRun;
}
public long getNextNumberToCheck() {
return nextNumberToCheck;
}
public void setNextNumberToCheck(long nextNumberToCheck) {
this.nextNumberToCheck = nextNumberToCheck;
}
public void setPosition(long position) throws IOException {
randomAccessFile.seek(position);
}
}