Refactoring to Reuse #5

#5 – Replace Custom Implementations With Open Source Equivalents

I realize this is a very large category with possibly several dozen examples. In this post, I will highlight this strategy using the Apache Commons IO API. Many applications require the need for accessing file data – reading input business data or even temporary file data is a common need. Typically, you have some class that opens a file, reads data line by line, and either returns a custom java object or a string buffer.

FileReader fr = null;
 BufferedReader reader = null;
 try {
 fr = new FileReader(strFileName);
 reader = new BufferedReader(fr);
 String line = reader.readLine();
 while (line != null) {
 //do something with the line of data...
 line = reader.readLine();
 } catch (IOException e) {
 } finally {
 try {
 if (reader != null) {
 } catch (IOException e) {

How many times have you written this kind of logic? 🙂 When you look to simplify this or want to reduce repetition, consider the Apache Commons IO library. The FileUtils class offers just the method you need for accomplishing the often needed line by line data access to a file. It is trivial to use. For example, see below:

//other lines of code and class declaration omitted...
String strFileName = //path to file...
try {
   File f = new File(strFileName);
   List fileDataLines = FileUtils.readLines(f, "UTF-8");
} catch (IOException ioe) {

That’s it – giving you the same functionality using a far simpler interface. There are several advantages to using these libraries – they are open-source, well documented and tested, and eliminate a lot of redundant code in your application. Travel light and only code stuff that you absolutely must. As I have highlighted before – reuse and agile go hand-in-hand. Less custom code you write, less maintenance for your team.


One Response to Refactoring to Reuse #5

  1. […] Object to XML using Freemarker I wrote earlier about using open source software for fulfilling functionality prior to building a custom implementation. Many projects have the need […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: