概述
我们先来看看Groovy都带来哪些新特性.
你只需很少的代码就可以读取一个文件:
number
=
0
new File( " src/aa.groovy " ).eachLine( {
line ->
number ++
println("$number:$line")
} )
new File( " src/aa.groovy " ).eachLine( {
line ->
number ++
println("$number:$line")
} )
打印一个集合:文字集合和简单的属性访问.
java.util.List 和 java.util.Map 可能是应用得最广泛的接口在Java里.但
是只有少量的语言支持.Groovy加入了声明list和map就像你声明一个string或number一样
简单,并且在集合类里加入了许多方法.
下面一个例子程序,打印出各个类所在的包.
def classes
=
[String,List,File]
for (clazz in classes)
{
println clazz.'package'.name
}
for (clazz in classes)
{
println clazz.'package'.name
}
操作XML:对于Java来说操作XML是一件很复杂的事情.
现在Groovy已经大简化了这种操作.假设有customer.xml:
<?
xml version
=
"
1.0
"
?>
< customers >
< corporate >
< customer name = " Bill Gates " company = " Microsoft " />
< customer name = " Steve Jobs " company = " Apple " />
< customer name = " Jonathan Schwartz " company = " Sun " />
</ corporate >
< consumer >
< customer name = " John Doe " />
< customer name = " Jane Doe " />
</ consumer >
</ customers >
你只需如下代码就可以访问此XML:
< customers >
< corporate >
< customer name = " Bill Gates " company = " Microsoft " />
< customer name = " Steve Jobs " company = " Apple " />
< customer name = " Jonathan Schwartz " company = " Sun " />
</ corporate >
< consumer >
< customer name = " John Doe " />
< customer name = " Jane Doe " />
</ consumer >
</ customers >
def customers
=
new
XmlSlurper().parse(
new
File(
"
src/customer.xml
"
))
for (customer in customers.corporate.customer)
{
println "${customer.@name} works for ${customer.@company}";
}
for (customer in customers.corporate.customer)
{
println "${customer.@name} works for ${customer.@company}";
}
最后
以上就是幸福万宝路为你收集整理的Groovy之旅系列之八(Groovy List&File&XML)的全部内容,希望文章能够帮你解决Groovy之旅系列之八(Groovy List&File&XML)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复