Guava工具類使用

Guava經常使用工具類學習

1、概述

Guava是對Java API的補充,對Java開發中經常使用功能進行更優雅的實現,使得編碼更加輕鬆,代碼容易理解。Guava使用了多種設計模式,同時通過了不少測試,獲得了愈來愈多開發團隊的青睞。Java最新版本的API採納了Guava的部分功能,但依舊沒法替代。本文以Getting Started With Google Guava原文爲學習材料,對Guava中經常使用的API進行學習,儘可能覆蓋比較有用的API,包括字符串處理,集合類處理,文件IO處理等。html

2、字符串鏈接器Joiner

2.1 鏈接多個字符串並追加到StringBuilderjava

StringBuilder stringBuilder = new StringBuilder("hello");
// 字符串鏈接器,以|爲分隔符,同時去掉null元素
Joiner joiner = Joiner.on("|").skipNulls();
// 構成一個字符串foo|bar|baz並添加到stringBuilder
stringBuilder = joiner.appendTo(stringBuilder, "foo", "bar", null, "baz");
System.out.println(stringBuilder); // hellofoo|bar|baz

2.2 鏈接List元素並寫到文件流設計模式

FileWriter fileWriter = null;
try {
    fileWriter = new FileWriter(new File("c:/tmp.txt"));
} catch (Exception e) {
    System.out.println(e.getMessage());
}
List<Date> dateList = new ArrayList<Date>();
dateList.add(new Date());
dateList.add(null);
dateList.add(new Date());
// 構造鏈接器:若是有null元素,替換爲no string
Joiner joiner = Joiner.on("#").useForNull("no string");
try {
    // 將list的元素的tostring()寫到fileWriter,是否覆蓋取決於fileWriter的打開方式,默認是覆蓋,如有true,則是追加
    joiner.appendTo(fileWriter, dateList);
    // 必須添加close(),不然不會寫文件
    fileWriter.close();
} catch (IOException e) {
    System.out.println(e.getMessage());
}

最後tmp.txt的內容爲:
Wed Apr 14 21:28:24 CST 2021#no string#Wed Apr 14 21:28:24 CST 2021數組

2.3 將Map轉化爲字符串app

Map<String, String> testMap = Maps.newLinkedHashMap();
testMap.put("Cookies", "12332");
testMap.put("Content-Length", "30000");
testMap.put("Date", "2016.12.16");
testMap.put("Mime", "text/html");
// 用:分割鍵值對,並用#分割每一個元素,返回字符串
String returnedString = Joiner.on("#").withKeyValueSeparator(":").join(testMap);
System.out.println(returnedString);
// Cookies:12332#Content-Length:30000#Date:2016.12.16#Mime:text/html

3、 字符串分割器Splitter

3.1 將字符串分割爲Iterableless

// 分割符爲|,並去掉獲得元素的先後空白
Splitter sp = Splitter.on("|").trimResults();
String str = "hello | world | your | Name ";
Iterable<String> ss = sp.split(str);
for(String it : ss){
    System.out.println(it);
}

結果爲:
hello
world
your
Name ide

3.2 將字符串轉化爲Map函數

// 內部類的引用,獲得分割器,將字符串解析爲map
String returnedString = "Cookies:12332#Content-Length:30000#Date:2016.12.16#Mime:text/html";
Splitter.MapSplitter ms = Splitter.on("#").withKeyValueSeparator(':');
Map<String, String> ret = ms.split(returnedString);
for(String it2 : ret.keySet()){
    System.out.println(it2 + " -> " + ret.get(it2));
}

結果爲:
Cookies -> 12332
Content-Length -> 30000
Date -> 2016.12.16
Mime -> text/html工具

4、 字符串工具類Strings

System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true
System.out.println(Strings.isNullOrEmpty("hello")); // false
// 將null轉化爲""
System.out.println(Strings.nullToEmpty(null)); // ""

// 從尾部不斷補充T只到總共8個字符,若是源字符串已經達到或操做,則原樣返回。相似的有padStart
System.out.println(Strings.padEnd("hello", 8, 'T')); // helloTTT

5、字符匹配器CharMatcher

5.1 空白一一替換學習

// 空白回車換行對應換成一個#,一對一換
String stringWithLinebreaks = "hello world\r\r\ryou are here\n\ntake it\t\t\teasy";
String s6 = CharMatcher.BREAKING_WHITESPACE.replaceFrom(stringWithLinebreaks,'#');
System.out.println(s6); // hello#world###you#are#here##take#it###easy

5.2 連續空白縮成一個字符

// 將全部連在一塊兒的空白回車換行字符換成一個#,倒塌
String tabString = "  hello   \n\t\tworld   you\r\nare             here  ";
String tabRet = CharMatcher.WHITESPACE.collapseFrom(tabString, '#');
System.out.println(tabRet); // #hello#world#you#are#here#

5.3 去掉先後空白和縮成一個字符

// 在前面的基礎上去掉字符串的先後空白,並將空白換成一個#
String tabString = "#hello#world#you#are#here#";
String trimRet = CharMatcher.WHITESPACE.trimAndCollapseFrom(tabString, '#');
System.out.println(trimRet);// hello#world#you#are#here

5.4 保留數字

String letterAndNumber = "1234abcdABCD56789";
// 保留數字
String number = CharMatcher.JAVA_DIGIT.retainFrom(letterAndNumber);
System.out.println(number);// 123456789

6、 斷言工具類Preconditions

// 檢查是否爲null,null將拋出異常IllegalArgumentException,且第二個參數爲錯誤消息。
String trimRet = null;
Preconditions.checkNotNull(trimRet, "label can not be null");
int data = 10;
Preconditions.checkArgument(data < 100, "data must be less than 100");

7、對象工具類 Objects

7.1 Objects的toStringHelper和hashCode方法

class Book implements Comparable<Book>{
    private String author;
    private String title;
    private String publisher;
    private String isbn;
    private double price;

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    // 定義第一二關鍵字
    @Override
    public int compareTo(Book o) {
        return ComparisonChain.start().compare(this.title, o.title).compare(this.isbn, o.isbn).result();
    }

    public String toString(){
        return MoreObjects.toStringHelper(this).omitNullValues().add("author", author).add("title", title)
            .add("publisher", publisher).add("isbn", isbn).add("price", price).toString();
    }

    public int hashCode(){
        return Objects.hashCode(author, title, publisher, isbn, price);
    }
}
// Book用Objects的相關方法簡化toString(),hashCode()的實現。
// 用ComparisonChain簡化compareTo()(Comparable接口)方法的實現。
Book book1 = new Book();
book1.setAuthor("Tom");
book1.setTitle("Children King");
book1.setIsbn("11341332443");
System.out.println(book1);
System.out.println(book1.hashCode());

Book book2 = new Book();
book2.setAuthor("Amy");
book2.setTitle("Children King");
book2.setIsbn("111");
System.out.println(book2);
System.out.println(book2.hashCode());

System.out.println(book1.compareTo(book2));

結果爲:
Book{author=Tom, title=Children King, isbn=11341332443, price=0.0}
268414056
Book{author=Amy, title=Children King, isbn=111, price=0.0}
-1726402621
1

7.2 Objects的firstNonNull方法

// 若是第一個爲空,則返回第二個,同時爲null,將拋出NullPointerException異常
String someString = null;
String value = MoreObjects.firstNonNull(someString, "default value");
System.out.println(value); // deafult value

8、總體迭代接口FluentIterable

8.1 使用Predicate總體過濾

class Person{
    private String name;
    private String sex;
    private int age;
    public Person(String name, int age, String sex){
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
            "name='" + name + '\'' +
            ", sex='" + sex + '\'' +
            ", age=" + age +
            '}';
    }
}
Person person1 = new Person("Wilma", 30, "F");
Person person2 = new Person("Fred", 32, "M");
Person person3 = new Person("Betty", 32, "F");
Person person4 = new Person("Barney", 33, "M");
List<Person> personList = Lists.newArrayList(person1, person2, person3, person4);

// 過濾年齡大於等於32的person
Iterable<Person> personsFilteredByAge =
    FluentIterable.from(personList).filter(new Predicate<Person>() {
    @Override
    public boolean apply(Person input) {
        return input.getAge() > 31;
    }
});

// Iterable有一個iterator方法,集合類都有一個Iterator方法
for(Iterator<Person> it = personsFilteredByAge.iterator(); it.hasNext();){
    System.out.println(it.next());
}
System.out.println(Iterables.contains(personsFilteredByAge, person2));

結果爲:
Person{name='Fred', sex='M', age=32}
Person{name='Betty', sex='F', age=32}
Person{name='Barney', sex='M', age=33}
true

8.2 使用Function總體替換,將List<Person>轉化爲List<String>

Person person1 = new Person("Wilma", 30, "F");
Person person2 = new Person("Fred", 32, "M");
Person person3 = new Person("Betty", 32, "F");
Person person4 = new Person("Barney", 33, "M");
List<Person> personList = Lists.newArrayList(person1, person2, person3, person4);

// 將List<Person> 轉化爲 List<String>,數據源爲personList。總體迭代。
List<String> transformPersonList = FluentIterable.from(personList).transform(
    new Function<Person, String>(){
        @Override
        public String apply(Person person) {
            // 不定參數,返回String類型
            return Joiner.on("#").join(person.getName(), person.getSex(), person.getAge());
        }
    }
).toList();
for(int i = 0; i < transformPersonList.size(); i++){
    System.out.println(transformPersonList.get(i));
}

結果爲:

Wilma#F#30
Fred#M#32
Betty#F#32
Barney#M#33

9、 集合運算工具類Sets

9.1 集合差

// s1 - s2
Set<String> s1 = Sets.newHashSet("1", "2", "3", "4");
Set<String> s2 = Sets.newHashSet("2", "3", "4", "5");
// 獲得第一個集合中有而第二個集合沒有的字符串
Sets.SetView res = Sets.difference(s1, s2);
for(Iterator<String> it = res.iterator(); it.hasNext();){
    System.out.println(it.next()); // 1
}

9.2 集合對稱差

Set<String> s1 = Sets.newHashSet("1", "2", "3", "4");
Set<String> s2 = Sets.newHashSet("2", "3", "4", "5");
Sets.SetView res2 = Sets.symmetricDifference(s1, s2);
for(Object it14 : res2){
    System.out.println(it14); // 1 5
}

9.3 集合交

Set<String> s1 = Sets.newHashSet("1", "2", "3", "4");
Set<String> s2 = Sets.newHashSet("2", "3", "4", "5");
// s1和s2的交集
Sets.SetView<String> res3 = Sets.intersection(s1, s2);
for(String it14 : res3){
    System.out.println(it14); // 2 3 4
}

9.4 集合並

Set<String> s1 = Sets.newHashSet("1", "2", "3", "4");
Set<String> s2 = Sets.newHashSet("2", "3", "4", "5");
// 合併s1和s2
Sets.SetView<String> res4 = Sets.union(s1, s2);
for(String it14 : res4){
    System.out.println(it14); // 1 2 3 4 5
}

10、Function和Predicate

10.1 利用Functions將Map轉化爲Function

Person person1 = new Person("Wilma", 30, "F");
Person person2 = new Person("Fred", 32, "M");
Person person3 = new Person("Betty", 32, "F");
Person person4 = new Person("Barney", 33, "M");
Map<String, Person> mp = Maps.newHashMap();
mp.put(person1.getName(), person1);
mp.put(person2.getName(), person2);
mp.put(person3.getName(), person3);
mp.put(person4.getName(), person4);
// 將map轉化爲Function,Function的功能是將一個類型轉化爲另外一個類型
Function<String, Person> lookup = Functions.forMap(mp);
// 若是鍵值不存在,則會拋出異常。lookup內部已經有元素
Person tmp = lookup.apply("Betty");
System.out.println(tmp == person3); // true

10.2 Predicate單個判斷

Person person1 = new Person("Wilma", 30, "F");
Person person2 = new Person("Fred", 32, "M");
Person person3 = new Person("Betty", 32, "F");
Person person4 = new Person("Barney", 33, "M");
Predicate<Person> agePre = new Predicate<Person>(){
    @Override
    public boolean apply(Person person) {
        return person.getAge() < 32;
    }
};
Predicate<Person> namePre = new Predicate<Person>(){
    @Override
    public boolean apply(Person person) {
        return person.getName().equals("Betty");
    }
};
// 判斷是否符合條件
System.out.println(agePre.apply(person2)); // false
System.out.println(agePre.apply(person3)); // false
System.out.println(namePre.apply(person2)); // false
System.out.println(namePre.apply(person3)); // true

10.3 Predicates的and運算

Person person1 = new Person("Wilma", 30, "F");
Person person2 = new Person("Fred", 32, "M");
Person person3 = new Person("Betty", 32, "F");
Person person4 = new Person("Barney", 33, "M");
Predicate<Person> agePre = new Predicate<Person>(){
    @Override
    public boolean apply(Person person) {
        return person.getAge() < 32;
    }
};
Predicate<Person> namePre = new Predicate<Person>(){
    @Override
    public boolean apply(Person person) {
        return person.getName().equals("Betty");
    }
};
// 利用Predicates工具類,同時知足兩個條件成一個predicate
Predicate<Person> both = Predicates.and(agePre, namePre);
System.out.println(both.apply(person1)); // false
System.out.println(both.apply(person3)); // false

10.4 Predicates的or運算

Person person1 = new Person("Wilma", 30, "F");
Person person2 = new Person("Fred", 32, "M");
Person person3 = new Person("Betty", 32, "F");
Person person4 = new Person("Barney", 33, "M");
Predicate<Person> agePre = new Predicate<Person>(){
    @Override
    public boolean apply(Person person) {
        return person.getAge() < 32;
    }
};
Predicate<Person> namePre = new Predicate<Person>(){
    @Override
    public boolean apply(Person person) {
        return person.getName().equals("Betty");
    }
};
// 至少一個知足組成一個Predicate
Predicate<Person> orPre = Predicates.or(agePre, namePre);
System.out.println(orPre.apply(person2)); // false

10.5 Predicates的compose運算

Person person1 = new Person("Wilma", 30, "F");
Person person2 = new Person("Fred", 32, "M");
Person person3 = new Person("Betty", 32, "F");
Person person4 = new Person("Barney", 33, "M");
Map<String, Person> mp = Maps.newHashMap();
mp.put(person1.getName(), person1);
mp.put(person2.getName(), person2);
mp.put(person3.getName(), person3);
mp.put(person4.getName(), person4);
Predicate<Person> agePre = new Predicate<Person>(){
    @Override
    public boolean apply(Person person) {
        return person.getAge() < 32;
    }
};
Predicate<Person> namePre = new Predicate<Person>(){
    @Override
    public boolean apply(Person person) {
        return person.getName().equals("Betty");
    }
};
// 經過鍵name得到值Person,而後檢查Person的age < 32,即agepre.apply(lookup.apply(name)) == true?
// lookup內部已經有集合
Function<String, Person> lookup = Functions.forMap(mp);
Predicate<String> two = Predicates.compose(agePre, lookup);
System.out.println(two.apply("Wilma")); // true

11、 Map工具類Maps

Person person1 = new Person("Wilma", 30, "F");
Person person2 = new Person("Fred", 32, "M");
Person person3 = new Person("Betty", 32, "F");
Person person4 = new Person("Barney", 33, "M");
List<Person> personList = Lists.newArrayList(person1, person2, person3, person4);
// 將List<Person> 轉化爲Map<String, Person>,其中鍵值對是person.name -> Person
Map<String, Person> myMp = Maps.uniqueIndex(personList, new Function<Person, String>(){
    // name做爲person的鍵
    @Override
    public String apply(Person person) {
        return person.getName();
    }
});
for(String name : myMp.keySet()){
    System.out.println(myMp.get(name));
}

結果爲:
Person{name='Wilma', sex='F', age=30}
Person{name='Fred', sex='M', age=32}
Person{name='Betty', sex='F', age=32}
Person{name='Barney', sex='M', age=33}

12、一鍵多值類Multimap

12.1 數組存儲多值類ArrayListMultimap

// 用ArrayList保存,一鍵多值,值不會被覆蓋
ArrayListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("foo", "1");
multimap.put("foo", "2");
multimap.put("foo", "3");
multimap.put("bar", "a");
multimap.put("bar", "a");
multimap.put("bar", "b");
for(String it20 : multimap.keySet()){
    // 返回類型List<String>
    System.out.println(it20 + " : " + multimap.get(it20));
}
// 返回全部ArrayList的元素個數的和
System.out.println(multimap.size());

結果爲:
bar : [a, a, b]
foo : [1, 2, 3]
6

12.2 HashTable存儲多值類 HashMultimap

//這裏採用HashTable保存
HashMultimap<String, String> hashMultimap = HashMultimap.create();
hashMultimap.put("foo", "1");
hashMultimap.put("foo", "2");
hashMultimap.put("foo", "3");
// 重複的鍵值對值保留一個
hashMultimap.put("bar", "a");
hashMultimap.put("bar", "a");
hashMultimap.put("bar", "b");
for(String it20 : hashMultimap.keySet()){
    // 返回類型List<String>
    System.out.println(it20 + " : " + hashMultimap.get(it20));
}
// 5
System.out.println(hashMultimap.size());

結果爲:
bar : [a, b]
foo : [1, 2, 3]
5

十3、多鍵類Table

13.1 兩個鍵操做

// 兩個鍵row key和column key,其實就是map中map, map<Integer, map<Integer, String> > mp
HashBasedTable<Integer, Integer, String> table = HashBasedTable.create();
table.put(1, 1, "book");
table.put(1, 2, "turkey");
table.put(2, 2, "apple");
System.out.println(table.get(1, 1)); // book
System.out.println(table.contains(2, 3)); // false
System.out.println(table.containsRow(2)); // true
table.remove(2, 2);
System.out.println(table.get(2, 2)); // null

13.2 獲取一個Map

// 兩個鍵row key和column key,其實就是map中map, map<Integer, map<Integer, String> > mp
HashBasedTable<Integer, Integer, String> table = HashBasedTable.create();
table.put(1, 1, "book");
table.put(1, 2, "turkey");
table.put(2, 2, "apple");

// 獲取單獨的一個map
Map<Integer, String> row = table.row(1);
Map<Integer, String> column = table.column(2);
System.out.println(row.get(1)); // book
System.out.println(column.get(1)); // turkey
System.out.println(column.get(2)); // turkey

十4、 能夠經過value獲取key的HashBiMap

14.1 value不能夠有相同的key

BiMap<String, String> biMap = HashBiMap.create();
// value能夠做爲Key,即value不能夠有多個對應的值
biMap.put("hello", "world");
biMap.put("123", "tell");
biMap.put("123", "none"); // 覆蓋tell
// biMap.put("abc", "world"); // 失敗
// 下面是強制替換第一對
biMap.forcePut("abc", "world");
System.out.println(biMap.size()); // 2
System.out.println(biMap.get("hello"));// null
System.out.println(biMap.get("abc")); // world
System.out.println(biMap.get("123")); // none

14.2 鍵值對互換獲得新的BiMap

BiMap<String, String> biMap = HashBiMap.create();
// value能夠做爲Key,即value不能夠有多個對應的值
biMap.put("hello", "world");
biMap.put("123", "tell");
biMap.put("123", "none"); // 覆蓋tell
// biMap.put("abc", "world"); // 失敗
// 下面是強制替換第一對
biMap.forcePut("abc", "world");

// 鍵值對互換
BiMap<String, String> inverseMap = biMap.inverse();
System.out.println(inverseMap.get("world")); // abc
System.out.println(inverseMap.get("tell")); // null
System.out.println(inverseMap.get(null)); // null

十5、不可變集合類ImmutableListMultimap

// 不可變的集合,都有一個Builder內部類。不能夠修改和添加
Multimap<Integer, String> map = new ImmutableListMultimap.Builder<Integer, String>().put(1, "hello")
    .putAll(2, "abc", "log", "in").putAll(3, "get", "up").build();
System.out.println(map.get(2)); // [abc, log, in]

十6、 區間工具類Range

// 閉區間
Range<Integer> closedRange = Range.closed(30, 33);
System.out.println(closedRange.contains(30)); // true
System.out.println(closedRange.contains(33)); // true

// 開區間
Range<Integer> openRange = Range.open(30, 33);
System.out.println(openRange.contains(30)); // false
System.out.println(openRange.contains(33)); // false

Function<Person, Integer> ageFunction = new Function<Person, Integer>(){
    @Override
    public Integer apply(Person person) {
        return person.getAge();
    }
};
Person person1 = new Person("Wilma", 30, "F");
// Range實現了Predicate接口,這裏的第一個參數是Predicate,第二個參數是Function
// ageFunction必須返回整數
Predicate<Person> agePredicate = Predicates.compose(closedRange, ageFunction);
System.out.println(agePredicate.apply(person1)); // person1.age == 30 true

十7、比較器工具類 Ordering

17.1 逆置比較器

// 自定義比較器,嵌入式的比較器,匿名類。注意這裏有兩個person參數,與Comparable的區別
Comparator<Person> ageCmp = new Comparator<Person>(){
    // Ints是Guava提供的,遞增
    @Override
    public int compare(Person o1, Person o2) {
        return Ints.compare(o1.getAge(), o2.getAge());
    }
};
List<Person> list = Lists.newArrayList(person1, person2, person3, person4);
// 將比較器轉化爲Ordering,獲得比較器ageCmp的相反比較器,遞減
Collections.sort(list, Ordering.from(ageCmp).reverse());
for(Iterator<Person> iter = list.iterator(); iter.hasNext(); ){
    System.out.println(iter.next());
}

結果爲:
Person{name='Barney', sex='M', age=33}
Person{name='Fred', sex='M', age=32}
Person{name='Betty', sex='F', age=32}
Person{name='Wilma', sex='F', age=30}

17.2 組合多個比較器

// 按照名字排序
Comparator<Person> nameCmp = new Comparator<Person>(){
    @Override // 兩個對象,而Comparable是this和一個對象
    public int compare(Person o1, Person o2) {
        return o1.getName().compareTo(o2.getName());
    }
};
// 組合兩個比較器,獲得第一二排序關鍵字
// 年齡相同時按照名字排序
Ordering order = Ordering.from(ageCmp).compound(nameCmp);
Collections.sort(list, order);
for(Iterator<Person> iter = list.iterator(); iter.hasNext(); ){
    System.out.println(iter.next());
}

結果爲:

Person{name='Wilma', sex='F', age=30}
Person{name='Betty', sex='F', age=32}
Person{name='Fred', sex='M', age=32}
Person{name='Barney', sex='M', age=33}

17.3 直接獲取最小几個和最大幾個

Ordering order2 = Ordering.from(nameCmp);
// 最小的兩個,無序
System.out.println("least 2...");
List<Person> least = order2.leastOf(personList, 2);
for(int i = 0; i < 2; i++){
    System.out.println(least.get(i));
}
// 最大的三個,無序
System.out.println("greatest 3....");
List<Person> great = order2.greatestOf(personList, 3);
for(int i = 0; i < 3; i++){
    System.out.println(great.get(i));
}

結果爲:
least 2...
Person{name='Barney', sex='M', age=33}
Person{name='Betty', sex='F', age=32}
greatest 3....
Person{name='Wilma', sex='F', age=30}
Person{name='Fred', sex='M', age=32}
Person{name='Betty', sex='F', age=32}

十8、 文件工具類Files

18.1 複製移動重命名文件

// 文件操做:複製,移動,重命名
File originFile = new File("C:/tmp.txt");
File copyFile = new File("C:/tmp_copy.txt");
File mvFile = new File("C:/tmp_move.txt");
try {
    Files.copy(originFile, copyFile);
    Files.move(copyFile, mvFile); // 重命名
} catch (IOException e) {
    e.printStackTrace();
}

18.2 獲取文件哈希碼

File originFile = new File("C:/tmp.txt");
File copyFile = new File("C:/tmp_copy.txt");
File mvFile = new File("C:/tmp_move.txt");

try {
    // File,HashFunction
    HashCode hashCode = Files.hash(originFile, Hashing.md5());
    System.out.println(originFile.getName() + " : " + hashCode);
} catch (IOException e) {
    e.printStackTrace();
}

結果爲:abc.java : 66721c8573de09bd17bafac125e63e98

18.3 讀取文件流,將文件行轉化爲List

// 文件操做:複製,移動,重命名
File originFile = new File("C:/tmp.txt");
File copyFile = new File("C:/tmp_copy.txt");
File mvFile = new File("C:/tmp_move.txt");

// 讀文件流
int lineNumber = 1;
try {
    // 讀出全部的行到list中,去掉\n
    List<String> list2 = Files.readLines(mvFile, Charsets.UTF_8);
    for(Iterator<String> it = list2.iterator(); it.hasNext();){
        System.out.println("line " + lineNumber + ":" + it.next());
        lineNumber++;
    }
} catch (IOException e) {
    e.printStackTrace();
}

結果

line 1:Wed Apr 14 21:28:24 CST 2021
line 2:#no string#Wed Apr 14 21:28:24 CST 2021

18.4 將文件行進行處理,再獲得List

class TitleLineProcessor implements LineProcessor<List<String>>{
    private final static int INDEX = 0;
    private final static Splitter splitter = Splitter.on(",");
    private List<String> titles = new ArrayList<String>();
    // 每一行都會調用這個函數,進而追加成一個list
    @Override
    public boolean processLine(String s) throws IOException {
        // 獲取第一項,並追加到titles
        titles.add(Iterables.get(splitter.split(s), INDEX));
        return true;
    }

    // 最終的結果
    @Override
    public List<String> getResult() {
        return titles;
    }
}
File bookFile = new File("C:/tmp.txt");
try {
    // 只取書名
    List<String> list3 = Files.readLines(bookFile, Charsets.UTF_8, new TitleLineProcessor());
    for(Iterator<String> it = list3.iterator(); it.hasNext();){
        System.out.println(it.next());
    }
} catch (IOException e) {
    e.printStackTrace();
}

十9、 讀輸入字節流ByteSource和寫輸出字節流ByteSink

File writeFile = new File("C:/tmp.txt");
// source是源的意思,封裝輸入流
ByteSource byteSource = Files.asByteSource(writeFile);
try {
    byte[] contents1 = byteSource.read();
    byte[] contents2 = Files.toByteArray(writeFile); // 兩個方法的做用相同
    for(int i = 0; i < contents1.length; i++){
        assert(contents1[i] == contents2[i]);
        System.out.print(contents1[i] + " ");
    }
} catch (IOException e) {
    e.printStackTrace();
}

// sink是目的地的意思,封裝輸出流,流會自動關閉
File tmpFile = new File("C:/tmp2.txt"); // acd
ByteSink byteSink = Files.asByteSink(tmpFile);
try {
    byteSink.write(new byte[]{'a', 'c', 'd', '\n'});
} catch (IOException e) {
    e.printStackTrace();
}

二10、 編碼工具類BaseEncoding

File writeFile = new File("C:/tmp.txt");
BaseEncoding baseEncoding = BaseEncoding.base64();
try {
    byte[] content = Files.toByteArray(writeFile);
    String encoded = baseEncoding.encode(content); // 將不可打印的字符串轉化爲能夠打印的字符串A-Za-z0-9/+=,pdf不是純文本文件
    System.out.println("encoded:\n" + encoded);
    System.out.println(Pattern.matches("[A-Za-z0-9/+=]+", encoded));
    // 得到對應的加密字符串,能夠解密,可逆的,獲得原來的字節
    byte[] decoded = baseEncoding.decode(encoded);
    for(int i = 0; i < content.length; i++){
        assert(content[i] == decoded[i]);
    }
} catch (IOException e) {
    e.printStackTrace();
}

二11、 提醒處理null的類Optional

Optional<Person> optional = Optional.fromNullable(person1); // 容許參數爲null
System.out.println(optional.isPresent()); // true
System.out.println(optional.get() == person1); // 若是是person1 == null,get將拋出IllegalStateException, true

Optional<Person> optional2 = Optional.of(person1); // 不容許參數爲null。若是person1 == null, 將拋出NullPointerException
System.out.println(optional2.isPresent()); // true
相關文章
相關標籤/搜索