guava 實用操作集合

jopen 8年前發布 | 15K 次閱讀 Java開發

guava是 google 幾個java核心類庫的集合,包括集合、緩存、原生類型、并發、常用注解、基本字符串操作和I/O等等。 
   
   大家平時經常遇到某些相同的問題,自己寫代碼也都能解決。但是久而久之會感覺到很痛苦,因為我們一而再,再而三的重復發明輪子。為了不再忍受痛苦,也許我們可以總結自己的類庫,但是新的問題來了。自己總結的類庫很難與大家分享,不能幫助到更多人。同時自己的類庫要不斷的進行維護。guava 正是出于這樣的目的而來的。 

   只說不練不行啊,讓我們舉上一兩個例子 
判斷 String不為null,且不為空 

Java代碼  收藏代碼

  1. String str=...;  

  2. //use java  

  3. if(str !=null && !str.isEmpty()){  

  4.     //do something  

  5. }  

  6.   

  7.   

  8. //use guava  

  9. if(!Strings.isNullOrEmpty(str)){  

  10.     //do something  

  11. }  


上而的例子還不是很給力,讓我們舉一個更給力的例子。復制文件 

Java代碼  收藏代碼

  1. File from=...;  

  2. File to=...;  

  3.   

  4. //use java  

  5. FileInputStream in=new FileInputStream(from);  

  6. FileOutputStream out=new FileOutputStream(to);  

  7. byte[] buff=new byte[1024];  

  8. int readLength=-1;  

  9. while((readLength = in.read(buff)) > 0){  

  10.     out.write(buff, 0, readLength);  

  11. }  

  12. in.close();  

  13. out.close();  

  14.   

  15. //use guava  

  16. Files.copy(from,to); //注意,只用了一行代碼噢  



    通過上面的例子,已經能感覺到guava的強大。接下來,讓我們更深入看看guava的其他功能。guava(r09-api)分為這幾個包 

  • base              基本的工具類與接口

  • io                 io流相關的工具類與方法

  • net               網絡地址相關的工具類與方法

  • primitives        原始類型的工具類

  • collect           通用集合接口與實現,與其集合相關工具類

  • util.concurrent 并發相關工具類



base包 

字符串相關工具類 
Strings 

Java代碼  收藏代碼

  1. public class StringsTest {  

  2.     @Test   

  3.     public void test() {  

  4.         //將空字符串轉換為null  

  5.         Assert.assertEquals(null, Strings.emptyToNull(""));  

  6.         //將null轉換為空字符串  

  7.         Assert.assertEquals("", Strings.nullToEmpty(null));  

  8.         //判斷字符串為null或者為空  

  9.         Assert.assertTrue(Strings.isNullOrEmpty("") && Strings.isNullOrEmpty(null));  

  10.         //將字符串重復  

  11.         Assert.assertEquals("javajavajava", Strings.repeat("java"3));  

  12.     }  

  13. }  



CharMatcher 

Java代碼  收藏代碼

  1. public class CharMatcherTest {  

  2.     @Test   

  3.     public void test() {  

  4.         String source = "a1b2c3";  

  5.         CharMatcher matcher = CharMatcher.DIGIT; //預定義的 DIGIT 類型  

  6.         Assert.assertTrue(mathcer.match('8'));  

  7.         Assert.assertEquals("123", matcher.retainFrom(source));  

  8.         Assert.assertEquals(3, matcher.countIn(source));  

  9.         Assert.assertEquals("abc", matcher.removeFrom(source));  

  10.         Assert.assertEquals("a2b3c", matcher.trimFrom("1a2b3c4"));  

  11.     }  

  12. }  


Jioner 

Java代碼  收藏代碼

  1. public class JoinerTest {  

  2.     @Test   

  3.     public void test() {  

  4.         Assert.assertEquals("2011-08-04", Joiner.on("-").join("2011""08""04"));  

  5.     }  

  6. }  



Splitter 

Java代碼  收藏代碼

  1. public class SplitterTest {  

  2.     @Test   

  3.     public void test() {  

  4.         Splitter.on(',').split("a,b"); //結果返回Iterable<String>,包含 "a" and "b"  

  5.         //將結果中的元素trim  

  6.         //結果依然包含  "a" 和 "b" ,而不是 "a " 和 " b"  

  7.         Splitter.on(',').trimResults().split("a , b");   

  8.         //忽略空字符串  

  9.         //結果必須是"a" 和 "b",而不是 "a" ,"" 和 "b"  

  10.         Splitter.on(',').omitEmptyStrings().split("a,,b");   

  11.     }  

  12. }  



CaseFormat 

Java代碼  收藏代碼

  1. public class CaseFormatTest {  

  2.   

  3.     @Test   

  4.     public void test() throws IOException {  

  5.         // helloGuava => HELLO_GUAVA  

  6.         Assert.assertEquals("HELLO_GUAVA", CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "helloGuava"));  

  7.         // hello-guava => HelloGuava  

  8.         Assert.assertEquals("HelloGuava", CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, "hello-guava"));  

  9.     }  

  10. }  



其他 
Preconditions 
有些方法在執行前,先要檢查傳入的參數是否正確,或者類的狀態是否正確。通常會這樣做

Java代碼  收藏代碼

  1. if (count <= 0) {  

  2.        throw new IllegalArgumentException("must be positive: " + count);  

  3. }  


guava就可以這樣,達到相同的效果 

Java代碼  收藏代碼

  1. Preconditions.checkArgument(count > 0"must be positive: %s", count);  



I/O包 
ByteStreams提供了針對字節流的工具方法 

Java代碼  收藏代碼

  1. InputStream from=...;  

  2. OutputStream to=...;  

  3. ByteStreams.copy(from,to); //復制  



CharStreams提供了針對字符流的工具方法 

Java代碼  收藏代碼

  1. Reader from =...;  

  2. Writer to =...;  

  3. CharStreams.copy(from, to); //復制  



Files提供了針對文件的工具方法 

Java代碼  收藏代碼

  1. File from=...;  

  2. File to=...;  

  3. Files.copy(from, to); //復制  


Java代碼  收藏代碼

  1. Files.deleteDirectoryContents(File directory); //刪除文件夾下的內容(包括文件與子文件夾)  

  2. Files.deleteRecursively(File file); //刪除文件或者文件夾  

  3. Files.move(File from, File to); //移動文件  



Resources提供了針對classpath下資源操作的工具方法 

Java代碼  收藏代碼

  1. URL url = Resources.getResource("config.xml"); //獲取classpath根下的config.xml文件url  


來自: http://bastengao.iteye.com/blog/1134887

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!