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 if (currLine != null && currLine.startsWith("<?xml")) {
46 return; // it's an xml file, it shouldn't use this cacher
48 while (currLine != null)
50 if (currLine.indexOf('\0') >= 0)
53 return; // it's a binary file, shouldn't use this cacher
55 if (currLine.trim().length() > 0)
56 contentList.add(currLine);
57 currLine = reader.readLine();
60 catch (IOException ioe) {}
63 // close file ignoring errors
66 if (reader != null) reader.close();
68 catch (Exception e) {}
71 // Convert into String array for keeps
72 int numLines = contentList.size();
73 _contentArray = new String[numLines];
74 for (int i=0; i<numLines; i++)
75 _contentArray[i] = contentList.get(i);
80 * @return Contents of the file as array of non-blank Strings
82 public String[] getContents()
89 * Get the top section of the file for preview
90 * @param inNumRows number of lines to extract
91 * @param inMaxWidth max length of Strings (longer ones will be chopped)
92 * @return String array containing non-blank lines from the file
94 public String[] getSnippet(int inNumRows, int inMaxWidth)
96 final int MIN_SNIPPET_SIZE = 3;
97 // Check size is within sensible limits
98 int numToCopy = inNumRows;
99 if (numToCopy > getNumLines()) numToCopy = getNumLines();
100 int size = numToCopy;
101 if (size < MIN_SNIPPET_SIZE) size = MIN_SNIPPET_SIZE;
102 String[] result = new String[size];
103 // Copy Strings across
104 System.arraycopy(_contentArray, 0, result, 0, numToCopy);
105 // Chop Strings to max width if necessary
108 for (int i=0; i<size; i++)
110 if (result[i] == null)
114 if (result[i].length() > inMaxWidth)
115 result[i] = result[i].trim();
116 if (result[i].length() > inMaxWidth)
117 result[i] = result[i].substring(0, inMaxWidth);
125 * @return the number of non-blank lines in the file
127 public int getNumLines()
129 return _contentArray.length;
139 _contentArray = null;