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) {
51 return; // it's a binary file, shouldn't use this cacher
53 if (currLine.trim().length() > 0)
54 contentList.add(currLine);
55 currLine = reader.readLine();
58 catch (IOException ioe) {}
61 // close file ignoring errors
64 if (reader != null) reader.close();
66 catch (Exception e) {}
69 // Convert into String array for keeps
70 int numLines = contentList.size();
71 _contentArray = new String[numLines];
72 for (int i=0; i<numLines; i++)
73 _contentArray[i] = contentList.get(i);
78 * @return Contents of the file as array of non-blank Strings
80 public String[] getContents()
87 * Get the top section of the file for preview
88 * @param inNumRows number of lines to extract
89 * @param inMaxWidth max length of Strings (longer ones will be chopped)
90 * @return String array containing non-blank lines from the file
92 public String[] getSnippet(int inNumRows, int inMaxWidth)
94 final int MIN_SNIPPET_SIZE = 3;
95 // Check size is within sensible limits
96 int numToCopy = inNumRows;
97 if (numToCopy > getNumLines()) numToCopy = getNumLines();
99 if (size < MIN_SNIPPET_SIZE) size = MIN_SNIPPET_SIZE;
100 String[] result = new String[size];
101 // Copy Strings across
102 System.arraycopy(_contentArray, 0, result, 0, numToCopy);
103 // Chop Strings to max width if necessary
106 for (int i=0; i<size; i++)
108 if (result[i] == null)
112 if (result[i].length() > inMaxWidth)
113 result[i] = result[i].trim();
114 if (result[i].length() > inMaxWidth)
115 result[i] = result[i].substring(0, inMaxWidth);
123 * @return the number of non-blank lines in the file
125 public int getNumLines()
127 return _contentArray.length;
137 _contentArray = null;