List of Java weapons

就像Elliotte说过的一样,thhe most efficient code is the code you never write. 这点在Java的世界特别明显。你总是能找到一些成熟的包来完成工作。下面这个列表维护一些日常工作中特别有用的武器,随时更新。不一定能在你公司的项目里面用,注意license,license,license。

StringUtils

commons-lang这个library实在是做得很棒。StringUtils提供了很多早就该被String纳入的实用的方法。

1
2
3
4
5
6
7
StringUtils.isEmpty(null) &&StringUtils.isEmpty(""); // true
StringUtils.isBlank("   \n\t");                       // true
StringUtils.substringAfterLast("foo.bar.baz", ".");   // "baz"
StringUtils.substringBeforeLast("foo.bar.baz", ".");  // "foo.bar"
StringUtils.split("foo.bar.baz", '.');                // { "foo", "bar", "baz" }
StringUtils.split("foo,  bar,baz", ", ");             // { "foo", "bar", "baz" }
StringUtils.leftPad("1", 3, '0');                     // "001"


IOUtils and FileUtils

commons-io提供的文件操作。虽然工作里面我们很少和文件打交道,但是一旦需要,你总是希望用它:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
File file1;
File file2;
InputStream inputStream;
OutputStream outputStream;
 
// 拷贝文件
FileUtils.copyFile(file1, file2);
IOUtils.copy(inputStream, outputStream);
 
// 把文件读成一个String
String s1 = FileUtils.readFileToString(file1);
String s2 = IOUtils.toString(inputStream);
 
// 按照换行把文件读成一个String List
List<String> l1 = FileUtils.readLines(file1);
List<String> l2 = IOUtils.readLines(inputStream);
 
// 在处理了stream之后,在finally()里面加入这个
IOUtils.closeQuietly(inputStream);
 
// 返回一个目录及其子目录下所有的xml和txt文件的List
Collection<File> c1 = FileUtils.listFiles(file1, { "xml", "txt" }, true);
 
// 拷贝文件夹
FileUtils.copyDirectoryToDirectory(file1, file2);
 
// 删除文件夹
FileUtils.deleteDirectory(file1);


Google collections

不然为什么叫Google呢,水准确实是高。一直有声音要把它加到JDK里面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 使用三要素创建ArrayList
List<String>list = Lists.newArrayList("foo", "bar", "baz");
 
// 没有generics也没有class cast,直接作成ConcurrentHashSet
 
Set<String> s = Sets.newConcurrentHashSet();
 
// Set的基本操作其实早就该有intersect了
Set&lt;String&gt; s = Sets.intersect(s1, s2);
 
// Map里面的多值情况
ListMultimap<String, Validator> validators = new ArrayListMultimap<String, Validator>();
validators.put("save", new RequiredValidator());
validators.put("save", new StringValidator());
validators.put("delete", new NumberValidator());
 
validators.get("save"); // { RequiredValidator, StringValidator }
validators.get("foo");  // empty List (not null)
validators.values();    // { RequiredValidator, StringValidator, NumberValidator }



[to be continued...]



Have your say

:want: :w00t: :tongue: :thrwon: :smile: :sick: :shock: :sad: :ninja: :getlost: :ermm: :dizzy: :devil: :cool: :boring: :blush: :blink: :angry: :angel:



Safari hates me


Douban Update

Get the Flash Player to see the slideshow.
去看看吧