X-Git-Url: http://gitweb.fperrin.net/?p=GpsPrune.git;a=blobdiff_plain;f=src%2Ftim%2Fprune%2Fload%2FFileCacher.java;fp=src%2Ftim%2Fprune%2Fload%2FFileCacher.java;h=a151c2e285022f48c5ffe8bbdf2c3d8433c09df0;hp=0000000000000000000000000000000000000000;hb=ce6f2161b8596f7018d6a76bff79bc9e571f35fd;hpb=2d8cb72e84d5cc1089ce77baf1e34ea3ea2f8465 diff --git a/src/tim/prune/load/FileCacher.java b/src/tim/prune/load/FileCacher.java new file mode 100644 index 0000000..a151c2e --- /dev/null +++ b/src/tim/prune/load/FileCacher.java @@ -0,0 +1,141 @@ +package tim.prune.load; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + +/** + * Class to load the contents of a file + * into an array for later retrieval + */ +public class FileCacher +{ + /** File to cache */ + private File _file = null; + /** Array to hold lines of file */ + private String[] _contentArray = null; + + + /** + * Constructor + * @param inFile File object to cache + */ + public FileCacher(File inFile) + { + _file = inFile; + loadFile(); + } + + + /** + * Load the specified file into memory + */ + private void loadFile() + { + ArrayList contentList = new ArrayList(); + if (_file != null && _file.exists() && _file.canRead()) + { + BufferedReader reader = null; + try + { + reader = new BufferedReader(new FileReader(_file)); + String currLine = reader.readLine(); + if (currLine != null && currLine.startsWith("= 0) + { + reader.close(); + return; // it's a binary file, shouldn't use this cacher + } + if (currLine.trim().length() > 0) + contentList.add(currLine); + currLine = reader.readLine(); + } + } + catch (IOException ioe) {} + finally + { + // close file ignoring errors + try + { + if (reader != null) reader.close(); + } + catch (Exception e) {} + } + } + // Convert into String array for keeps + int numLines = contentList.size(); + _contentArray = new String[numLines]; + for (int i=0; i getNumLines()) numToCopy = getNumLines(); + int size = numToCopy; + if (size < MIN_SNIPPET_SIZE) size = MIN_SNIPPET_SIZE; + String[] result = new String[size]; + // Copy Strings across + System.arraycopy(_contentArray, 0, result, 0, numToCopy); + // Chop Strings to max width if necessary + if (inMaxWidth > 10) + { + for (int i=0; i inMaxWidth) + result[i] = result[i].trim(); + if (result[i].length() > inMaxWidth) + result[i] = result[i].substring(0, inMaxWidth); + } + } + } + return result; + } + + /** + * @return the number of non-blank lines in the file + */ + public int getNumLines() + { + return _contentArray.length; + } + + + /** + * Clear the memory + */ + public void clear() + { + _file = null; + _contentArray = null; + } +}