Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava, Files.readLines() and white space

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?

like image 521
mip Avatar asked Dec 21 '22 20:12

mip


2 Answers

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;}
  });
like image 137
Louis Wasserman Avatar answered Jan 03 '23 12:01

Louis Wasserman


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.

like image 20
Xaerxess Avatar answered Jan 03 '23 13:01

Xaerxess