Easily compare a list of Strings with the contents of a file

Context: you need to check that the values you have in a List of Strings are the same as the contents of a file. An element in the List will correspond to an entire line from the file. How can you achieve this easily?

Well, first, let’s see what the data to compare is. Let’s go with an example, and assume that your List of Strings contains the following values: “apples”, ”pears”, ”cherries”, ”peaches”, ”plums”. The file that you need to compare the List to has the following structure:

apples
pears
cherries
peaches
plums

You can easily see that the contents of the List and the contents of the file are the same, as they all contain the same names of some very much-loved fruit. Testing this can be done in several ways of course, but below you will find a suggestion using the FileUtils class from the Apache Commons library. Specifically, we will use the ‘readLines’ method from this class.

Writing the test that will check the equality of the two will start with the import of the ‘readLines’, which I will do as a static import, so I can shorten the call to the method from the test:

import static org.apache.commons.io.FileUtils.readLines;

Let us assume the name of the List of Strings is ‘fruitList’. I will not go over how you create a List of Strings. Also, let’s assume that the path of the file containing the fruit names is ‘filePath’. I will not go over how the fruit names were added to the file either. The comparison between the List and the contents of the file (remember, we are checking an element of the list to a line of the file, based on position – first element with first line, second element with second line, etc.), will be done using an ‘assertEquals’, as follows:

assertEquals(readLines(new File(“filePath”)), fruitList);

The ‘readLines’ method returns a List of Strings, so the comparison will be done, in fact, between two Lists. Hence, the order is also checked to be the same, when using assertEquals (the order of the elements in the List needs to be the same as the order of the lines in the file, for the assertEquals to return true).

One thought on “Easily compare a list of Strings with the contents of a file”

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.