/* * DiskStrategy.java * Copyright (C) 2006 Amin Ahmad * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.ahmadsoft.postal; import java.io.File; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; /** * A retrieval strategy that looks up from disk every time. There is * almost no reason to use this strategy except in an interactive program * because, due to the fact that lookups are synchronized, and that every * lookup results in a disk access, its time characteristics are very poor. * However, its space requirements are constant. * * @author Amin Ahmad */ public class DiskStrategy implements PostalRetrievalStrategy { private RandomAccessFile dataFile; private RandomAccessFile indexFile; public void initialize(File _indexFile, File _dataFile) throws Exception { dataFile = new RandomAccessFile(_dataFile, "r"); indexFile = new RandomAccessFile(_indexFile, "r"); } public synchronized List getCandidates(int postalCode) { if (postalCode < 1 || postalCode > 99999) { return new ArrayList(); } List result = new ArrayList(); try { indexFile.seek((postalCode-1) * 8); indexFile.readInt(); int loc = indexFile.readInt(); dataFile.seek(loc); short type=0; while (0 != (type=dataFile.readShort())) { String state = dataFile.readUTF(); String city = dataFile.readUTF(); result.add(new PostalCodeEntry(postalCode,city,state,type)); } } catch (Exception e) { throw new RuntimeException(e); } return result; } public void dispose() throws Exception { dataFile.close(); indexFile.close(); } }