番石榴,Files.readLines()和白色空间 [英] Guava, Files.readLines() and white space

查看:162
本文介绍了番石榴,Files.readLines()和白色空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  List< String>下面的代码使用了Guava的Files.readLines strings = Lists.newArrayList(); 
final File file = new File(filePath);
if(file.isFile()){
try {
strings = Files.readLines(file,Charsets.UTF_8);

catch(IOException ioe){}
}
else {
//文件不存在
}

一旦我有我的字符串列表我想测试,看看我正在看的当前字符串是在文件中。

 字符串myString =foo; 
if(strings.contains(myString)){
//做某事
}

然而,我想让代码容忍原始文件包含前导或尾随空格(即foo)。



实现这一目标的最优雅的方法是什么? 解决方案

我能想到的tskuzzy的方法如下:

  List< String> trimmedLines = Files.readLines(File,Charsets.UTF_8,
)LineProcessor< List< String>>(){
List< String> result = Lists.newArrayList();

public boolean processLine(String line){
result.add(line.trim());
}
public List< String> getResult(){return result;}
});


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;}
  });

这篇关于番石榴,Files.readLines()和白色空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆