在学习Groovy的语法及其方法的时候,我偶尔看到了Groovy中对于txt文件引入输出的方法:
String content = new File('config.txt').text
println content
而对比java中对于文件的引用和输出的代码块:
// 1. 使用File类打开一个文件;
File file = new File("d:" + File.separator + "test.txt");
// 2. 通过字节流或字符流的子类指定输出的位置
InputStream fis = new FileInputStream(file);
// 3. 进行读操作
byte[] buf = new byte[1024]; // 所有的内容读到此数组中临时存放
int len; //用于记录读取的数据个数
String myStr = "";
while((len = fis.read(buf)) != -1) { //将内容读到byte数组中,同时返回个数,若为-1,则内容读到底
myStr += new String(buf, 0, len, "UTF-8");
}
// 4. 关闭输出
fis.close();
System.out.println(myStr);
我们可以看到Groovy的代码更为简单,而在java里面,要创建文件类,然后通过创建一个流来读取出文件内容,而要关闭文件流,非常的累赘。我想在这篇博客探究一下,Groovy中是重新编写了相关的功能类还是对java的功能类进行了拓展,并由此展开,就让我们继续往下叙述。
Groovy中text方法源码分析在对Groovy层层剖解下,我们发现了实现的最终方法:
//这个方法是在IOGroovyMethods类中
public static String getText(BufferedReader reader) throws IOException {
StringBuilder answer = new StringBuilder();
char[] charBuffer = new char[8192];
try {
int nbCharRead;
while((nbCharRead = reader.read(charBuffer)) != -1) {
answer.append(charBuffer, 0, nbCharRead);
}
Reader temp = reader;
reader = null;
temp.close();
} finally {
closeWithWarning(reader);
}
return answer.toString();
}
通过这段代码可以看到,Groovy底层的实现与Java原来的实现完全一样,只是Groovy替我们完成了封装,使得我们可以直接通过getText()方法来得到整个文本文件的内容。而在IOGroovyMethods里面,很多都是一些把Java类进行封装的拓展方法,细细查看分析后,发现是对IO文件操作的一些拓展方法。所以类IOGroovyMethods是一个对java的过于IO操作的拓展封装类。
由局部推向整体在IOGroovyMethods类里面,我们通过源码分析查看可以发现它继承于父类DefaultGroovyMethodsSupport,而在IOGroovyMethods所在的包org/codehaus/groovy/runtime里面,我们发现还有其它的类也是继承于DefaultGroovyMethodsSupport的,下面放出它们的类UML图:
DefaultGroovyMethods应该是对java任何类的一个拓展,里面的方法具有普遍性:
//用来直接判断other对象是否与调用对象相等
public static boolean is(Object self, Object other) {
return self == other;
}
//直接判断迭代器中的对象是否是唯一的
public static Iterator unique(Iterator self) {
return toList((Iterable)unique(toList(self))).listIterator();
}
public static Collection unique(Collection self) {
return unique(self, true);
}
//任意对象都都可以使用each方法来进行遍历,当然如果是不可迭代对象,会报错
public static T each(T self, Closure closure) {
each(InvokerHelper.asIterator(self), closure);
return self;
}
StringGroovyMethods类
StringGroovyMethods是对String字符串的封装功能拓展的一个封装功能类
//将String首字母大写,这个方法非常的常用,尤其在自定义Task时候
public static String capitalize(CharSequence self) {
return self.length() == 0?"":"" + Character.toUpperCase(self.charAt(0)) + self.subSequence(1, self.length());
}
//判断String是否为null或长度是否大于零
public static boolean asBoolean(CharSequence chars) {
if (chars != null) {
return chars.length() > 0;
} else {
return false;
}
}
DateGroovyMEthods类
DateGroovyMEthods类里面应该是对时间日期的一些封装拓展方法
//将传入的日期加一
@Deprecated
public static Calendar next(Calendar self) {
Calendar result = (Calendar)self.clone();
result.add(5, 1);
return result;
}
//日期相加
public static Date plus(Date self, int days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(self);
calendar.add(5, days);
return calendar.getTime();
}
总结:
Groovy里面有着许多可以间接使用的封装方法,而上述的便是这些方法的封装类,我们把这几个类都了解的话就基本可以知道groovy对java做了哪些方面的扩展。,通过这几个类的扩展方法,可以让我们编写的POJO和POGO类有更多常用的方法,可以极大的提高我们的开发效率。



