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
| import java.io.IOException;
import java.util.List;
public interface MyFileDAO {
List<String> getHead(Integer count) throws IOException;
List<String> getChunk(Integer start, Integer end) throws IOException;
List<String> getTail(Integer count) throws IOException;
Integer getNbLines();
}
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MyFileDAOImpl implements MyFileDAO {
private final Map<Integer, Long> indexes;
private final RandomAccessFile raf;
private final File file;
private Integer nbLines;
public MyFileDAOImpl(File f) throws IOException {
indexes = new HashMap<Integer, Long>(500);
file = f;
raf = new RandomAccessFile(f, "r");
computeIndexes();
}
private void computeIndexes() throws IOException {
nbLines = 0;
while (raf.getFilePointer() != raf.length()) {
indexes.put(nbLines, raf.getFilePointer());
raf.readLine();
nbLines++;
}
}
public List<String> getChunk(Integer start, Integer end) throws IOException {
final List<String> lines = new ArrayList<String>(start - end + 1);
final Long pos = indexes.get(start);
raf.seek(pos);
for (int i = start; i <= end; ++i) {
lines.add(raf.readLine());
}
return lines;
}
public List<String> getHead(Integer count) throws IOException {
return getChunk(0, count);
}
public List<String> getTail(Integer count) throws IOException {
return getChunk(getNbLines() - count, getNbLines() - 1);
}
public Integer getNbLines() {
return nbLines;
}
} |
Partager