本月初发布了新版本的Guava库,其中包含一些新功能和改进。
以下是此版本中一些重要的API新增功能的概述:
1.逃脱者
Escapers
使您可以“转义”字符串中的特殊字符,以使字符串符合特定格式。 例如,在XML中,必须将<
字符转换为<
用于包含在XML元素中。 番石榴提供以下逃脱者:
-
HtmlEscapers
-
XmlEscapers
-
UrlEscapers
您也可以构建自己的Escaper
。 这是各种Escapers
的例子:
// escaping HTML
HtmlEscapers.htmlEscaper().escape("echo foo > file &");
// [result] echo foo > file &// escaping XML attributes and content
XmlEscapers.xmlAttributeEscaper().escape("foo \"bar\"");
// [result] echo "bar"XmlEscapers.xmlContentEscaper().escape("foo \"bar\"");
// [result] foo "bar"// Custom Escaper
// escape single quote with another single quote
// and escape ampersand with backslash
Escaper myEscaper = Escapers.builder().addEscape('\'', "''").addEscape('&', "\&").build();
2. StandardSystemProperty
StandardSystemProperty
是Java系统属性的枚举,例如java.version
, java.home
等。关于此的很棒的事情是,您不再需要记住调用系统属性的原因,因为您只需使用枚举即可! 这是一个例子:
StandardSystemProperty.JAVA_VERSION.value();
// [result] 1.7.0_25StandardSystemProperty.JAVA_VERSION.key();
// [result] java.version
3.驱逐队列
EvictingQueue
是一个无阻塞队列,当队列已满并且您尝试插入新元素时,它将从队列的开头删除元素。 例:
// create an EvictingQueue with a size of 3
EvictingQueue<String> q = EvictingQueue.create(3);
q.add("one");
q.add("two");
q.add("three");
q.add("four");
// the head of the queue is evicted after adding the fourth element
// queue contains: [two, three, four]
4. fileTreeTraverser
顾名思义, Files.fileTreeTraverser
允许您遍历文件树。
FluentIterable<File> iterable = Files.fileTreeTraverser().breadthFirstTraversal(new File("/var/tmp"));
for (File f : iterable) {System.out.println(f.getAbsolutePath());
}
(注意:Java 7的Files.walkFileTree
也遍历文件树,我在以前的一篇文章中向您展示了如何使用它: Java 7:通过遍历文件树来删除目录 。如果您使用Java,则建议您使用这种方法7)
番石榴15的完整发行说明可以在这里找到。
参考: Guava 15 –我们的JCG合作伙伴 Fahd Shariff在fahd.blog博客上的新功能 。
翻译自: https://www.javacodegeeks.com/2013/10/guava-15-new-features.html