Commons Lang 包常用方法

本文通过多个示例介绍了Apache Commons Lang库中的实用工具类,包括字符串操作、对象比较、序列化、随机字符串生成等功能,展示了如何简化日常开发任务。
很多常用的功能就不用自己去实现了,使用commons里面自带的实现更方便。
001 public class TestLangDemo {
002  
003     public void charSetDemo() {
004         System.out.println("**CharSetDemo**");
005         CharSet charSet = CharSet.getInstance("aeiou");
006         String demoStr = "The quick brown fox jumps over the lazy dog.";
007         int count = 0;
008         for (int i = 0, len = demoStr.length(); i < len; i++) {
009             if (charSet.contains(demoStr.charAt(i))) {
010                 count++;
011             }
012         }
013         System.out.println("count: " + count);
014     }
015  
016     public void charSetUtilsDemo() {
017         System.out.println("**CharSetUtilsDemo**");
018         System.out.println("计算字符串中包含某字符数.");
019         System.out.println(CharSetUtils.count("The quick brown fox jumps over the lazy dog.""aeiou"));
020  
021         System.out.println("删除字符串中某字符.");
022         System.out.println(CharSetUtils.delete("The quick brown fox jumps over the lazy dog.""aeiou"));
023  
024         System.out.println("保留字符串中某字符.");
025         System.out.println(CharSetUtils.keep("The quick brown fox jumps over the lazy dog.""aeiou"));
026  
027         System.out.println("合并重复的字符.");
028         System.out.println(CharSetUtils.squeeze("a  bbbbbb     c dd""b d"));
029     }
030  
031     public void objectUtilsDemo() {
032         System.out.println("**ObjectUtilsDemo**");
033         System.out.println("Object为null时,默认打印某字符.");
034         Object obj = null;
035         System.out.println(ObjectUtils.defaultIfNull(obj, "空"));
036  
037         System.out.println("验证两个引用是否指向的Object是否相等,取决于Object的equals()方法.");
038         Object a = new Object();
039         Object b = a;
040         Object c = new Object();
041         System.out.println(ObjectUtils.equals(a, b));
042         System.out.println(ObjectUtils.equals(a, c));
043  
044         System.out.println("用父类Object的toString()方法返回对象信息.");
045         Date date = new Date();
046         System.out.println(ObjectUtils.identityToString(date));
047         System.out.println(date);
048  
049         System.out.println("返回类本身的toString()方法结果,对象为null时,返回0长度字符串.");
050         System.out.println(ObjectUtils.toString(date));
051         System.out.println(ObjectUtils.toString(null));
052         System.out.println(date);
053     }
054  
055     public void serializationUtilsDemo() {
056         System.out.println("*SerializationUtils**");
057         Date date = new Date();
058         byte[] bytes = SerializationUtils.serialize(date);
059         System.out.println(ArrayUtils.toString(bytes));
060         System.out.println(date);
061  
062         Date reDate = (Date) SerializationUtils.deserialize(bytes);
063         System.out.println(reDate);
064         System.out.println(ObjectUtils.equals(date, reDate));
065         System.out.println(date == reDate);
066  
067         FileOutputStream fos = null;
068         FileInputStream fis = null;
069         try {
070             fos = new FileOutputStream(new File("d:/test.txt"));
071             fis = new FileInputStream(new File("d:/test.txt"));
072             SerializationUtils.serialize(date, fos);
073             Date reDate2 = (Date) SerializationUtils.deserialize(fis);
074  
075             System.out.println(date.equals(reDate2));
076  
077         catch (FileNotFoundException e) {
078             e.printStackTrace();
079         finally {
080             try {
081                 fos.close();
082                 fis.close();
083             catch (IOException e) {
084                 e.printStackTrace();
085             }
086         }
087  
088     }
089  
090     public void randomStringUtilsDemo() {
091         System.out.println("**RandomStringUtilsDemo**");
092         System.out.println("生成指定长度的随机字符串,好像没什么用.");
093         System.out.println(RandomStringUtils.random(500));
094  
095         System.out.println("在指定字符串中生成长度为n的随机字符串.");
096         System.out.println(RandomStringUtils.random(5"abcdefghijk"));
097  
098         System.out.println("指定从字符或数字中生成随机字符串.");
099         System.out.println(RandomStringUtils.random(5truefalse));
100         System.out.println(RandomStringUtils.random(5falsetrue));
101  
102     }
103  
104     public void stringUtilsDemo() {
105         System.out.println("**StringUtilsDemo**");
106         System.out.println("将字符串重复n次,将文字按某宽度居中,将字符串数组用某字符串连接.");
107         String[] header = new String[3];
108         header[0] = StringUtils.repeat("*"50);
109         header[1] = StringUtils.center("  StringUtilsDemo  "50"^O^");
110         header[2] = header[0];
111         String head = StringUtils.join(header, "\n");
112         System.out.println(head);
113  
114         System.out.println("缩短到某长度,用...结尾.");
115         System.out.println(StringUtils.abbreviate("The quick brown fox jumps over the lazy dog."10));
116         System.out.println(StringUtils.abbreviate("The quick brown fox jumps over the lazy dog."1510));
117  
118         System.out.println("返回两字符串不同处索引号.");
119         System.out.println(StringUtils.indexOfDifference("aaabc""aaacc"));
120  
121         System.out.println("返回两字符串不同处开始至结束.");
122         System.out.println(StringUtils.difference("aaabcde""aaaccde"));
123  
124         System.out.println("截去字符串为以指定字符串结尾的部分.");
125         System.out.println(StringUtils.chomp("aaabcde""de"));
126  
127         System.out.println("检查一字符串是否为另一字符串的子集.");
128         System.out.println(StringUtils.containsOnly("aad""aadd"));
129  
130         System.out.println("检查一字符串是否不是另一字符串的子集.");
131         System.out.println(StringUtils.containsNone("defg""aadd"));
132  
133         System.out.println("检查一字符串是否包含另一字符串.");
134         System.out.println(StringUtils.contains("defg""ef"));
135         System.out.println(StringUtils.containsOnly("ef""defg"));
136  
137         System.out.println("返回可以处理null的toString().");
138         System.out.println(StringUtils.defaultString("aaaa"));
139         System.out.println("?" + StringUtils.defaultString(null) + "!");
140  
141         System.out.println("去除字符中的空格.");
142         System.out.println(StringUtils.deleteWhitespace("aa  bb  cc"));
143  
144         System.out.println("分隔符处理成数组.");
145         String[] strArray = StringUtils.split("a,b,,c,d,null,e"",");
146         System.out.println(strArray.length);
147         System.out.println(strArray.toString());
148  
149         System.out.println("判断是否是某类字符.");
150         System.out.println(StringUtils.isAlpha("ab"));
151         System.out.println(StringUtils.isAlphanumeric("12"));
152         System.out.println(StringUtils.isBlank(""));
153         System.out.println(StringUtils.isNumeric("123"));
154     }
155  
156     public void systemUtilsDemo() {
157         System.out.println(genHeader("SystemUtilsDemo"));
158         System.out.println("获得系统文件分隔符.");
159         System.out.println(SystemUtils.FILE_SEPARATOR);
160  
161         System.out.println("获得源文件编码.");
162         System.out.println(SystemUtils.FILE_ENCODING);
163  
164         System.out.println("获得ext目录.");
165         System.out.println(SystemUtils.JAVA_EXT_DIRS);
166  
167         System.out.println("获得java版本.");
168         System.out.println(SystemUtils.JAVA_VM_VERSION);
169  
170         System.out.println("获得java厂商.");
171         System.out.println(SystemUtils.JAVA_VENDOR);
172     }
173  
174     public void classUtilsDemo() {
175         System.out.println(genHeader("ClassUtilsDemo"));
176         System.out.println("获取类实现的所有接口.");
177         System.out.println(ClassUtils.getAllInterfaces(Date.class));
178  
179         System.out.println("获取类所有父类.");
180         System.out.println(ClassUtils.getAllSuperclasses(Date.class));
181  
182         System.out.println("获取简单类名.");
183         System.out.println(ClassUtils.getShortClassName(Date.class));
184  
185         System.out.println("获取包名.");
186         System.out.println(ClassUtils.getPackageName(Date.class));
187  
188         System.out.println("判断是否可以转型.");
189         System.out.println(ClassUtils.isAssignable(Date.class, Object.class));
190         System.out.println(ClassUtils.isAssignable(Object.class, Date.class));
191     }
192  
193     public void stringEscapeUtilsDemo() {
194         System.out.println(genHeader("StringEcsapeUtils"));
195         System.out.println("转换特殊字符.");
196         System.out.println("html:" + StringEscapeUtils.escapeHtml3(" "));
197         System.out.println("html:" + StringEscapeUtils.escapeHtml4(" "));
198         System.out.println("html:" + StringEscapeUtils.unescapeHtml3("<p>"));
199         System.out.println("html:" + StringEscapeUtils.unescapeHtml4("<p>"));
200     }
201  
202     private final class BuildDemo {
203         String name;
204         int age;
205  
206         public BuildDemo(String name, int age) {
207             this.name = name;
208             this.age = age;
209         }
210  
211         public String toString() {
212             ToStringBuilder tsb = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE);
213             tsb.append("Name", name);
214             tsb.append("Age", age);
215             return tsb.toString();
216         }
217  
218         public int hashCode() {
219             HashCodeBuilder hcb = new HashCodeBuilder();
220             hcb.append(name);
221             hcb.append(age);
222             return hcb.hashCode();
223         }
224  
225         public boolean equals(Object obj) {
226             if (!(obj instanceof BuildDemo)) {
227                 return false;
228             }
229             BuildDemo bd = (BuildDemo) obj;
230             EqualsBuilder eb = new EqualsBuilder();
231             eb.append(name, bd.name);
232             eb.append(age, bd.age);
233             return eb.isEquals();
234         }
235     }
236  
237     public void builderDemo() {
238         System.out.println(genHeader("BuilderDemo"));
239         BuildDemo obj1 = new BuildDemo("a"1);
240         BuildDemo obj2 = new BuildDemo("b"2);
241         BuildDemo obj3 = new BuildDemo("a"1);
242  
243         System.out.println("toString()");
244         System.out.println(obj1);
245         System.out.println(obj2);
246         System.out.println(obj3);
247  
248         System.out.println("hashCode()");
249         System.out.println(obj1.hashCode());
250         System.out.println(obj2.hashCode());
251         System.out.println(obj3.hashCode());
252  
253         System.out.println("equals()");
254         System.out.println(obj1.equals(obj2));
255         System.out.println(obj1.equals(obj3));
256     }
257  
258     public void numberUtils() {
259         System.out.println(genHeader("NumberUtils"));
260         System.out.println("字符串转为数字(不知道有什么用).");
261         System.out.println(NumberUtils.toInt("ba"33));
262  
263         System.out.println("从数组中选出最大值.");
264         System.out.println(NumberUtils.max(new int[] { 1234 }));
265  
266         System.out.println("判断字符串是否全是整数.");
267         System.out.println(NumberUtils.isDigits("123.1"));
268  
269         System.out.println("判断字符串是否是有效数字.");
270         System.out.println(NumberUtils.isNumber("0123.1"));
271     }
272  
273     public void dateFormatUtilsDemo() {
274         System.out.println(genHeader("DateFormatUtilsDemo"));
275         System.out.println("格式化日期输出.");
276         System.out.println(DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
277  
278         System.out.println("秒表.");
279         StopWatch sw = new StopWatch();
280         sw.start();
281  
282         for (Iterator iterator = DateUtils.iterator(new Date(), DateUtils.RANGE_WEEK_CENTER); iterator.hasNext();) {
283             Calendar cal = (Calendar) iterator.next();
284             System.out.println(DateFormatUtils.format(cal.getTime(), "yy-MM-dd HH:mm"));
285         }
286  
287         sw.stop();
288         System.out.println("秒表计时:" + sw.getTime());
289  
290     }
291  
292     private String genHeader(String head) {
293         String[] header = new String[3];
294         header[0] = StringUtils.repeat("*"50);
295         header[1] = StringUtils.center("  " + head + "  "50"^O^");
296         header[2] = header[0];
297         return StringUtils.join(header, "\n");
298     }
299  
300     private void validateDemo() {
301         String[] strarray = { "a""b""c" };
302         System.out.println("验证功能");
303         System.out.println(Validate.notEmpty(strarray));
304     }
305  
306     private void wordUtilsDemo() {
307         System.out.println("单词处理功能");
308         String str1 = "wOrD";
309         String str2 = "ghj\nui\tpo";
310         System.out.println(WordUtils.capitalize(str1)); // 首字母大写
311         System.out.println(WordUtils.capitalizeFully(str1)); // 首字母大写其它字母小写
312         char[] ctrg = { '.' };
313         System.out.println(WordUtils.capitalizeFully("i aM.fine", ctrg)); // 在规则地方转换
314         System.out.println(WordUtils.initials(str1)); // 获取首字母
315         System.out.println(WordUtils.initials("Ben John Lee"null)); // 取每个单词的首字母
316         char[] ctr = { ' ''.' };
317         System.out.println(WordUtils.initials("Ben J.Lee", ctr)); // 按指定规则获取首字母
318         System.out.println(WordUtils.swapCase(str1)); // 大小写逆转
319         System.out.println(WordUtils.wrap(str2, 1)); // 解析\n和\t等字符
320     }
321  
322     /**
323      * @param args
324      */
325     public static void main(String[] args) {
326         TestLangDemo langDemo = new TestLangDemo();
327  
328         langDemo.charSetDemo();
329         langDemo.charSetUtilsDemo();
330         langDemo.objectUtilsDemo();
331         langDemo.serializationUtilsDemo();
332         langDemo.randomStringUtilsDemo();
333         langDemo.stringUtilsDemo();
334         langDemo.systemUtilsDemo();
335         langDemo.classUtilsDemo();
336         langDemo.stringEscapeUtilsDemo();
337         langDemo.builderDemo();
338         langDemo.numberUtils();
339         langDemo.dateFormatUtilsDemo();
340         langDemo.validateDemo();
341         langDemo.wordUtilsDemo();
342     }
343  
344 }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值