Gradle文件集合

2020-07-24 16:00 更新

文件集合表示一組文件,Gradle 使用 FileCollection 接口表示文件集合, Gradle API 中的許多項目都實現了這個接口,例如 dependency configurations .

獲取 FileCollection 實例的一種方法是使用 Project.files() 方法.你可以傳遞任何數量的對象參數,這個方法能將你傳遞的對象集合轉換為一組文件對象.files() 方法接收任何類型對象參數.每一個 file()方法都依賴于項目目錄(在第 15 章,第一小節(jié)中介紹).files()方法也接收 collections, iterables,maps 和 arrays 類型參數.這些參數的內容會被解析,然后被轉換為文件對象.

例 15.2 創(chuàng)建文件集合

build.gradle

FileCollection collection = files('src/file1.txt',
                                  new File('src/file2.txt'),
                                  ['src/file3.txt', 'src/file4.txt'])

文件集合可以被迭代器,使用迭代操作能夠將其轉換為其他的一些類型.你可以使用 + 操作將兩個文件集合合并,使用 - 操作能夠對一個文件集合做減法.下面一些例子介紹如何操作文件集合.

例 15.3 使用文件集合

build.gradle

// 對文件集合進行迭代
collection.each {File file ->
    println file.name
}

// 轉換文件集合為其他類型
Set set = collection.files
Set set2 = collection as Set
List list = collection as List
String path = collection.asPath
File file = collection.singleFile
File file2 = collection as File

// 增加和減少文件集合
def union = collection + files('src/file3.txt')
def different = collection - files('src/file3.txt')

你也可以向 files() 方法專遞一個閉合或者可回調的實例參數.當查詢集合的內容時就會調用它,然后將返回值轉換為一些文件實例.返回值可以是 files() 方法支持的任何類型的對象.下面有個簡單的例子來演示實現 FileCollection 接口

例 15.4 實現一個文件集合

build.gradle

task list << {
    File srcDir

    // 使用閉合創(chuàng)建一個文件集合
    collection = files { srcDir.listFiles() }

    srcDir = file('src')
    println "Contents of $srcDir.name"
    collection.collect { relativePath(it) }.sort().each { println it }

    srcDir = file('src2')
    println "Contents of $srcDir.name"
    collection.collect { relativePath(it) }.sort().each { println it }
}

使用 gradle -q list 輸出結果

> gradle -q list
Contents of src
src/dir1
src/file1.txt
Contents of src2
src2/dir1
src2/dir2

另外, files() 方法也接收其他類型的參數:

FileCollection

內容損壞的文件包含在文件集合中.

Task

任務的輸出文件包含在文件集合中.

TaskOutputs

TaskOutputs 的輸出文件包含在文件集合中

值得注意的是當有需要時文件集合的內容會被被惰性處理,就比如一些任務在需要的時候會創(chuàng)建一個FileCollecion 代表的文件集合.


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號