public static String[] loadFile(final String f) {
String thisLine;
final SortedSet<String> s = new TreeSet<String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(f));
while ((thisLine = br.readLine()) != null)
s.add(thisLine.trim());
} catch (IOException ioe) {
System.err.println("Error reading file " + f);
throw new RuntimeException(ioe);
} finally {
if(br!=null) try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return s.toArray(new String[s.size()]);
}
Refactorings
No refactoring yet !
foo
November 25, 2008, November 25, 2008 08:18, permalink
One disadvantage with your approach is that since Sets do not allow duplicate elements, duplicate lines will be lost.
Alternatively, you could just add them to some kind of List (ArrayList or LinkedList will do) and then sort it.
public static String[] loadFile(final String f) {
String thisLine;
final List<String> s = new ArrayList<String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(f));
while ((thisLine = br.readLine()) != null)
s.add(thisLine.trim());
} catch (IOException ioe) {
System.err.println("Error reading file " + f);
throw new RuntimeException(ioe);
} finally {
if(br!=null) try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Collections.sort(s);
return s.toArray(new String[s.size()]);
}
Has full "finally" blocks, passes findBugs check, should be speedy using TreeSet. Useful for loading data files.