@@ -9,7 +9,6 @@ public class FileHandler implements AutoCloseable { | |||
private String dbFileName; | |||
private final int INT_LENGTH = 4; | |||
private final int BYTE_LENGTH = 1; | |||
private HashMap<Integer, Integer> indexes = new HashMap<>(); | |||
public FileHandler(String dbFileName) throws FileNotFoundException { | |||
this.dbFileName = dbFileName; | |||
@@ -117,7 +116,7 @@ public class FileHandler implements AutoCloseable { | |||
pos += lenRecord; | |||
} | |||
else { | |||
indexes.put(idx, pos); | |||
Index.getInstance().set(idx, pos); | |||
//dbFile.seek(pos); // optional: readBoolean sets pointer at pos + 1 byte | |||
lenRecord = dbFile.readInt(); | |||
pos += INT_LENGTH; | |||
@@ -148,8 +147,4 @@ public class FileHandler implements AutoCloseable { | |||
public void close() throws IOException { | |||
dbFile.close(); | |||
} | |||
public void printIndexes() { | |||
System.out.println(indexes.toString()); | |||
} | |||
} |
@@ -0,0 +1,43 @@ | |||
package cc.javastudio.raw; | |||
import java.util.HashMap; | |||
public final class Index { | |||
private static Index instance = new Index(); | |||
private HashMap<Long, Long> indexes = new HashMap<>(); | |||
private long totalRows = 0; | |||
private Index() {} | |||
public static Index getInstance() { | |||
return instance; | |||
} | |||
public void set(long index, long position) { | |||
if (!indexes.containsKey(index)) { | |||
totalRows++; | |||
} | |||
indexes.put(index, position); | |||
} | |||
/** | |||
* Searches for the position in a file of an index | |||
* @param index index to find the position of | |||
* @return -1 if not found; index position >= 0 when found | |||
*/ | |||
public long get(long index) { | |||
return indexes.getOrDefault(index, -1l); | |||
//return indexes.getOrDefault(index, (long)-1); | |||
} | |||
public long getTotalRows() { | |||
return totalRows; | |||
} | |||
public void remove(long index) { | |||
if (indexes.containsKey(index)) { | |||
indexes.remove(index); | |||
totalRows--; | |||
} | |||
} | |||
} |