1 package tim.prune.load;
3 import java.io.BufferedReader;
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.util.ArrayList;
10 * Class to load the contents of a file
11 * into an array for later retrieval
13 public class FileCacher
15 private File _file = null;
16 private String[] _contentArray = null;
21 * @param inFile File object to cache
23 public FileCacher(File inFile)
31 * Load the specified file into memory
33 private void loadFile()
35 ArrayList contentList = new ArrayList();
36 if (_file != null && _file.exists() && _file.canRead())
38 BufferedReader reader = null;
41 reader = new BufferedReader(new FileReader(_file));
42 String currLine = reader.readLine();
43 while (currLine != null)
45 if (currLine.trim().length() > 0)
46 contentList.add(currLine);
47 currLine = reader.readLine();
50 catch (IOException ioe) {}
53 // close file ignoring errors
56 if (reader != null) reader.close();
58 catch (Exception e) {}
61 // Convert into String array for keeps
62 int numLines = contentList.size();
63 _contentArray = new String[numLines];
64 for (int i=0; i<numLines; i++)
65 _contentArray[i] = contentList.get(i).toString();
70 * @return Contents of the file as array of non-blank Strings
72 public String[] getContents()
79 * Get the top section of the file for preview
80 * @param inNumRows number of lines to extract
81 * @param inMaxWidth max length of Strings (longer ones will be chopped)
82 * @return String array containing non-blank lines from the file
84 public String[] getSnippet(int inNumRows, int inMaxWidth)
86 final int MIN_SNIPPET_SIZE = 3;
87 // Check size is within sensible limits
88 int numToCopy = inNumRows;
89 if (numToCopy > getNumLines()) numToCopy = getNumLines();
91 if (size < MIN_SNIPPET_SIZE) size = MIN_SNIPPET_SIZE;
92 String[] result = new String[size];
93 // Copy Strings across
94 System.arraycopy(_contentArray, 0, result, 0, numToCopy);
95 // Chop Strings to max width if necessary
98 for (int i=0; i<size; i++)
100 if (result[i] == null)
104 if (result[i].length() > inMaxWidth)
105 result[i] = result[i].trim();
106 if (result[i].length() > inMaxWidth)
107 result[i] = result[i].substring(0, inMaxWidth);
115 * @return the number of non-blank lines in the file
117 public int getNumLines()
119 return _contentArray.length;
129 _contentArray = null;