Read text from a URL

Develop a java program that reads in strings from the following URL and stores them in a sorted list.

Problem Specification

Develop a java program that reads in strings from the following URL and stores them in a sorted list.

The user should then be able to enter a sub-string and the program should return a list of matching strings that contain the substring. All matching strings should be displayed, sorted and the search should be case insensitive.

Implementation Steps

package algorithms;

import java.util.List;

public interface StringSearchInterface {

  public abstract List<String> getSubstringList(String subString);

  public abstract void addString(String s);

}

As you have not covered networking or exceptions in Java I’ve included a link to an example constructor for WordList(NOTE: it’s not complete!). However you should try to to figure out how to read from a URL yourself using the web (Try googling “read from url java”). Example constructor excerpt here:

  public WordList(String urlString) throws IOException {

    BufferedReader in = null;
    try {
      wordList = new ArrayList<String>();
      in = new BufferedReader(new InputStreamReader(new URL(urlString).openStream()));
      String inputLine;
      while ((inputLine = in.readLine()) != null)
        wordList.add(inputLine);
    }
    finally {
      if (in != null)
        in.close();
    }
  }

JUint Test

package algorithms;

import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;

public class WordListTest {

  private static final String url = "http://dl.dropbox.com/u/18678304/2011/BSc2/words.txt";

  @Test
  public void testAddString() throws Exception {
    StringSearchInterface wordList;
    String s = "I Love Javaaaaaa!";
    String searchString = "love";

    wordList = new WordList(url);

    wordList.addString(s);
    System.out.println(wordList.getSubstringList(searchString).size());
    // check that the search returned some results
    assertTrue(wordList.getSubstringList(s).size() == 1);

  }

  @Test
  public void testGetSubstringList() throws Exception {
    StringSearchInterface wordList;
    String s = "umb";

    wordList = new WordList(url);
    List<String> resultList = wordList.getSubstringList(s);

    // check that the search returned some result(i.e. there is a match
    // in the list)
    assertTrue(resultList.size() > 0);

  }

  @Test
  public void testWordList() throws Exception {
    StringSearchInterface wordList;

    wordList = new WordList(url);
    assertNotNull(wordList);
  }
}