4100acda45394fa4e8efc805a486b732

Has full "finally" blocks, passes findBugs check, should be speedy using TreeSet. Useful for loading data files.

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 !

D41d8cd98f00b204e9800998ecf8427e

foo

November 25, 2008, November 25, 2008 08:18, permalink

2 ratings. Login to rate!

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()]);
	}
Ae8489eb86685b95cf1bd02ca19373f1

Matt

April 10, 2010, April 10, 2010 18:34, permalink

No rating. Login to rate!

Bleh...

Your refactoring





Format Copy from initial code

or Cancel