I have the following code which utilises Guava's Files.readLines() method:
List<String> strings = Lists.newArrayList();
final File file = new File(filePath);
if (file.isFile()) {
  try {
    strings= Files.readLines(file, Charsets.UTF_8);
  }
  catch (IOException ioe) {}
}
else {
  // File does not exist
}
Once I have my List of String I'd like to test to see if a current String which I am looking at was in the file.
String myString = "foo";
if (strings.contains(myString)) {
  // Do something
}
However, I'd like to make the code tolerant to the original file contain leading or trailing spaces (i.e. " foo ").
What is the most elegant way of achieving this?
The only alternative to tskuzzy's approach that I can think of is as follows:
List<String> trimmedLines = Files.readLines(file, Charsets.UTF_8,
  new LineProcessor<List<String>>() {
    List<String> result = Lists.newArrayList();
    public boolean processLine(String line) {
      result.add(line.trim());
    }
    public List<String> getResult() {return result;}
  });
You don't have to iterate over whole file (if you want to know only if line is in file), use Files.readLines(File file, Charset charset, LineProcessor<T> callback)
public final class Test {
  /**
   * @param args
   * @throws IOException
   */
  public static void main(final String[] args) throws IOException {
    test1("test");
  }
  static void test1(final String lineToTest) throws IOException {
    final Boolean contains = Files.readLines(new File("test.txt"), Charsets.UTF_8, new LineProcessor<Boolean>() {
      Boolean containsGivenLine = false;
      @Override
      public Boolean getResult() {
        return containsGivenLine;
      }
      @Override
      public boolean processLine(final String line) throws IOException {
        if (line.trim().equals(lineToTest)) {
          containsGivenLine = true;
          return false;
        } else {
          return true;
        }
      }
    });
    System.out.println("contains '" + lineToTest + "'? " + contains);
  }
Given file:
  test  
me   
   if  
 you want!
it outputs true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With