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
16 private File _file = null;
17 /** Array to hold lines of file */
18 private String[] _contentArray = null;
23 * @param inFile File object to cache
25 public FileCacher(File inFile)
33 * Load the specified file into memory
35 private void loadFile()
37 ArrayList<String> contentList = new ArrayList<String>();
38 if (_file != null && _file.exists() && _file.canRead())
40 BufferedReader reader = null;
43 reader = new BufferedReader(new FileReader(_file));
44 String currLine = reader.readLine();
45 while (currLine != null)
47 if (currLine.trim().length() > 0)
48 contentList.add(currLine);
49 currLine = reader.readLine();
52 catch (IOException ioe) {}
55 // close file ignoring errors
58 if (reader != null) reader.close();
60 catch (Exception e) {}
63 // Convert into String array for keeps
64 int numLines = contentList.size();
65 _contentArray = new String[numLines];
66 for (int i=0; i<numLines; i++)
67 _contentArray[i] = contentList.get(i);
72 * @return Contents of the file as array of non-blank Strings
74 public String[] getContents()
81 * Get the top section of the file for preview
82 * @param inNumRows number of lines to extract
83 * @param inMaxWidth max length of Strings (longer ones will be chopped)
84 * @return String array containing non-blank lines from the file
86 public String[] getSnippet(int inNumRows, int inMaxWidth)
88 final int MIN_SNIPPET_SIZE = 3;
89 // Check size is within sensible limits
90 int numToCopy = inNumRows;
91 if (numToCopy > getNumLines()) numToCopy = getNumLines();
93 if (size < MIN_SNIPPET_SIZE) size = MIN_SNIPPET_SIZE;
94 String[] result = new String[size];
95 // Copy Strings across
96 System.arraycopy(_contentArray, 0, result, 0, numToCopy);
97 // Chop Strings to max width if necessary
100 for (int i=0; i<size; i++)
102 if (result[i] == null)
106 if (result[i].length() > inMaxWidth)
107 result[i] = result[i].trim();
108 if (result[i].length() > inMaxWidth)
109 result[i] = result[i].substring(0, inMaxWidth);
117 * @return the number of non-blank lines in the file
119 public int getNumLines()
121 return _contentArray.length;
131 _contentArray = null;