Gradle의 모든 포스팅은 유튜브 프리렉을 기반으로 작성되었습니다.
링크 : https://www.youtube.com/watch?v=s-XZ5B15ZJ0&list=PL7mmuO705dG2pdxCYCCJeAgOeuQN1seZz
강의의 버전이 옛버전 이기 때문에 이론적인 부분만 학습하는것이 좋습니다.
1. 파일 관리 - (1)파일 참조
하나의 파일 참조
- File 객체의 file() 이용
- file() : 상대 경로나 File 객체를 인수로 사용
ex) File reffile = file('src/main/java/actJava.java')
File reffile = file(new File('src/refLib.txt'))
실습
File reffile = file('src/refJavaFile.java')
File reffile = file(new File('src/refExeFile.txt'))
task exeTask<<{
println'Java File Path :' + refFile1.absolutePath
println'Txt File Path :' + refFile2.path
}
gradle exeTask 실행결과
Java File Path : D:\workspace\경로\src\refJavaFile.java
Txt File Path : D:\workspace\경로\src\refExeFile.txt
URI 객체를 이용한 참조
File reffile = file('src/refJavaFile.java')
File reffile = file(new File('src/refExeFile.txt'))
task exeTask<<{
println'Java File Path :' + refFile1.absolutePath
println'Txt File Path :' + refFile2.path
}
//URL Object
File urlRef = null
URL url = new URL('file:/urlRef.html')
urlRef = file(url)
task exeTask<<{
println'URL Path:' + urlRef.path
}
gradle exeTask 실행결과
Java File Path : D:\workspace\경로\src\refJavaFile.java
Txt File Path : D:\workspace\경로\src\refExeFile.txt
URI Path : D:\workspace\경로\urlRef.html
URI 객체를 이용한 참조
//URI Object
File uriRef = null
URI uri = new URI('file:/uriRcf.html')
uriRef = file(uri)
클로저를 인수로 지정
// 클로저
File close = file('/ref.txt')
JAVA에서 제공하는 Callable 인터페이스
// Callabel 인터페이스
import.java.util.concurrent.Callable
File callRef = file(new Callable<string>(){
String call(){
'/refExe.java'
}
})
gradle exeTask 실행결과
Java File Path : D:\workspace\경로\src\refJavaFile.java
Txt File Path : D:\workspace\경로\src\refExeFile.txt
URI Path : D:\workspace\경로\urlRef.html
closer Path : D:\workspace\경로\ref.txt
Callable Path : D:\workspace\경로\refExe.java
파일 객체의 파일 검증
1. PathValidation.DIRECTORY 디렉터리 경로가 올바른지 검증(디렉터리 유무 확인)
2. PathValidation.FILE파일 경로가 올바른지 검증(파일 유무 확인)
3. PathValidation.EXISTS파일 또는 디렉터리 존재 여부 확인
4. PathValidation.NONE파일 검증 하지 않음
File checkFile=file('/index.html', PathValidation.FILE)
File checkDirectory=file('src', PathCalidation.DIRECTORY)
1. 파일 관리 - (2)다중 파일 참조
FileCollection 인터페이스
https://docs.gradle.org/current/javadoc/org/gradle/api/file/FileCollection.html
FileCollection (Gradle API 7.2)
Returns the contents of this collection as a Set. The contents of a file collection may change over time. Note that this method returns File objects that represent locations on the file system. These File objects do not necessarily refer to regular files.
docs.gradle.org
FileCollection
임의의 파일 index.txt, intro.txt 파일 생성 후 실습
FileCollection fileCollection = files('index.txt','intro.txt')
println'collection files : ' + fileCollection[0].path
println'collection files : ' + fileCollection[1].path
fileCollection.each{
println it.name + " : " + it.path
}
gradle 실행결과
> Configure project :
collection files : D:\workspace\경로\index.txt
collection files : D:\workspace\경로\intro.txt
index.txt : D:\workspace\경로\index.txt
intro.txt : D:\workspace\경로\intro.txt
FileCollection 다양한 인수 지정
// files()다양한 인수 지정
FileCollection fileCollection =
files('index.txt',new File('intro.txt'), new URL('file:/web.html'), new URI('file:/log.xml'))
fileCollection.each{
println it.name + " : " + it.path
}
gradle 실행결과
> Configure project :
index.txt : D:\workspace\경로\index.txt
intro.txt : D:\workspace\경로\intro.txt
web.html : D:\workspace\경로\web.html
log.xml : D:\workspace\경로\log.xml
FileCollection 리스트형 지정
// 리스트형 지정
List fileList = [new File('intro.txt'),new File('index.txt'),new File('log.txt')]
FileCollection fileCollection1 = files(fileList)
fileCollection1.each{
println 'file List 1 :' + it.name + " : " + it.path
}
// 배열로 지정
FileCollection fileCollection2 = files(fileList as File[])
// as 연산자를 이용
fileCollection2.each{
println'file Array 2 : ' + it.name + " : " + it.path
}
gradle 실행결과
> Configure project :
file List 1 : intro.txt : D:\workspace\경로\intro.txt
file List 1 : index.txt : D:\workspace\경로\index.txt
file List 1 : log.txt : D:\workspace\경로\log.txt
file Array 2 : intro.txt : D:\workspace\경로\intro.txt
file Array 2 : index.txt : D:\workspace\경로\index.txt
file Array 2 : log.txt : D:\workspace\경로\log.txt
as연산자 사용
파일 컬렉션 변환
// 파일 컬렉션 변환
FileCollection fileCollection =
files('settings.txt',new File('intro.txt'),new File('index.txt'),new File('log.txt'))
List 형으로 변환
// List 형으로 변환
List fileList = fileCollection as List
fileList.each{
println'List collection : ' + it.path
}
Set 형으로 변환
Set fileSet = fileCollection as Set
fileSet.each{
println'Set collection :' + it.path
}
배열로 변환
// 배열로 변환
File[] fileArray = fileCollection as File[]
fileArray.each{
println'Array collection:' + it.path
}
gradle 실행결과
> Configure project :
List collection : D:\workspace\경로\settings.txt
List collection : D:\workspace\경로\intro.txt
List collection : D:\workspace\경로\index.txt
List collection : D:\workspace\경로\log.txt
Set collection : D:\workspace\경로\settings.txt
Set collection : D:\workspace\경로\intro.txt
Set collection : D:\workspace\경로\index.txt
Set collection : D:\workspace\경로\log.txt
Array collection : D:\workspace\경로\settings.txt
Array collection : D:\workspace\경로\intro.txt
Array collection : D:\workspace\경로\index.txt
Array collection : D:\workspace\경로\log.txt
FileCollection의 덧셈 연산자
// FileCollection의 덧셈 연산자
FileCollection fc1 = files('log.txt')
FileCollection fc2 = fc1 + files('intro.txt')
if(fc2.files.size() == 2){
println 'fc2.file count :' + fc2.file.size()
fc2.each{
println'fc2 file =>'+it.name + ":" +it.path
}
}
gradle 실행결과
> Configure project :
fc2 file count : 2
fc2 file => log.txt : D:\workspace\경로\log.txt
fc2 file => intro.txt : D:\workspace\경로\intro.txt
FileCollection의 뺄셈 연산자
// FileCollection의 뺄셈 연산자
FileCollection fc1 = files('log.txt','intro.txt')
FileCollection fc2 = fc1 + files('intro.txt')
// 뺄셈 연산자를 통해 intro.txt파일 제외
if(fc2.files.size() == 1){
println 'fc2.file count :' + fc2.file.size()
fc2.each{
println'fc2 file =>'+it.name + ":" +it.path
}
}
gradle 실행결과
> Configure project:
fc2 file count : 1
fc2 file => log.txt : D:\workspace\경로\log.txt
FileCollection 필터링
필터링 : 조건을 지정하여 조건에 부합하는 파일만 참조하도록 할 수 있다.
// FileCollection 필터링
FileCollection fileCollection =
files('settings.txt', 'login.txt',new File('intro.java'),
new File('index.html'),new File('log.txt'))
println 'All File Size : ' + fileCollection.files.size()
// 텍스트 파일에 대하여 필터링
FileCollection txtFilter1 =
fileCollection.filter{
collectionFile.name.endsWith'.txt'
}
println 'File Filter Size :' + txtFilter1.files.size()
// 필터링된 파일 내용 출력
txtFilter1.each{
println 'txtFilter1 file =>' '+it.name + ":" + it.path
}
gradle 실행결과
> Configure project :
All File Size : 5
File Filter Size : 3
txtFilter1 file => settings.txt : D:\workspace\경로\settings.txt
txtFilter1 file => login.txt : D:\workspace\경로\login.txt
txtFilter1 file => log.txt : D:\workspace\경로\log.txt
총 파일이 5개가 있지만 filter를 통하여
txt로 끝나는 파일들만 참조하고 있다.
1. 파일 관리 - (3)FileTree 파일 참조
FileTree
https://docs.gradle.org/current/javadoc/org/gradle/api/file/FileTree.html
FileTree (Gradle API 7.2)
Restricts the contents of this tree to those files matching the given filter. The filtered tree is live, so that any changes to this tree are reflected in the filtered tree. The given pattern set is used to configure the filter. Only files which match the
docs.gradle.org
여러개의 파일을 FileCollection과 같이 참조할 수 있다.
FileTree만의 특징을 알아보자
FileTree
FileTree fileTree = fileTree('settings')
fileTree.each{
println'File Name:' + it.name + ', Path: ' + it.path
}
실습예제 파일경로
gradle 실행결과
> Configure project :
File Name : settings.gradle, Path : D:\workspace\경로\settings\settings.gradle
FileTree 인터페이스에서 참조하고 있는 파일명과 파일경로 출력
클로저를 이용한 FilreTree 객체 생성
FileTreefileTreeEx = file('src'){
include'**/*.java'
}
src 디렉터리를 기준으로 참조중인 파일 내용 출력
fileTreeEx.each{
println'1. fileTree Name : ' + it.name
}
src 디렉터리를 기준으로 특정 파일 제외
fileTreeEx = fileTree('src'){
exclude '**/action????.java'
}
src 디렉터리를 기준으로 참조중인 파일 내용 출력
fileTreeEx.each{
println '2. fileTree Name :' + it.name
}
임의대로 java파일 생성 후
gradle 실행결과
> Configure project :
1. fileTree Name : actionTest.java
1. fileTree Name : fileDAO.java
1. fileTree Name : fileSpring.java
1. fileTree Name : fileTree.java
2. fileTree Name : fileDAO.java
2. fileTree Name : fileSpring.java
2. fileTree Name : fileTree.java
action파일 제외 된것을 확인 가능
'**/action????.java' 에서 확인가능한 앤트 패턴 표현식
앤트패턴 표현식
표현 방법 | 설명 |
* | 임의 문자열로 길이에 제한 없이 패턴으로 처리 *.java(확장자가 java인 파일) |
? | 임의 문자에 대하여 패턴으로 처리 예)action?.java: action 다음에 어느 문자가 되었든 하나의 문자에 대하여 일치하는 자바 파일 예)action????.java: 여러 문자에 대하여 지정할 경우 문자의 개수만큼 사용 |
** | 임의 계층의 디렉터리 예) **/*.java: 지정된 디렉터리를 기준으로 하위 디렉터리 모두에 포함된 자바 파일 |
MAP을 이용한 FileTree 객체 생성
// MAP을 이용한 FileTree 객체 생성
FileTree fileMap = fileTree(dir:'src',include:'**/*.java',exclude:'**/action????.java')
fileMap.each{
println 'fileMap Name :' + it.name
}
match()를 이용한 파일 참조
match()는 filter와 비슷한 성격을 가지고 있는 메서드이다.
조건에 맞는 파일에 대해서 FileTree 객체를 생성할 수 있도록 한다.
include나 exclude를 사용해야 한다.
// matching()
FileTree fileMatch = fileTree('src')
// FileTree 객체 생성 src 폴더의 하위에 있는 파일들을 참조
FileTree ft1 = fileMatch.matching{
include'**/*.java'
// .java로 끝나는 파일을 참조하도록
}
ft1.each{
println '1. File Name : ' + it.name
}
FileTree ft2 = fileMatch.matching{
exclude '**/action????.java'
// action????.java 파일을 제외하도록
}
ft2.each{
println'2. File Name :' + it.name
}
visit(), isDirectory()를 이용한 파일 참조
fileTree fileVisit = fileTree('src')
fileVisit.visit { fileDetails ->
// vist메소드를 이용해서 fileTree구조의 load를? 탐색하기 위해
println 'fileVisit File Name :' + fileDetails.getName()
if(fileDetails.isDirectory()) {
// 디렉토리 유무를 체크
println ' isDirectory Yes : ' +
fileDetails.getPath() + ' size :' +
fileDetails.getSize()
} else{
println' isDirectory NO :' +
fileDetails.getPath() + ' size :' +
fileDetails.getSize()
}
}
gradle 실행결과
> Configure project :
fileVisit File Name : actionTest.java
isDirectory No : actionTest.java size : 36
fileVisit File Name : com
isDirectory Yes : com size : 0
fileVisit File Name : test
isDirectory Yes : com/test size : 0
fileVisit File Name : dir
isDirectory Yes : com/test/dir size : 0
fileVisit File Name : dirTest.java
isDirectory No : com/test/dir/dirTest.java size : 54
fileVisit File Name : fileDAO.java
isDirectory No : fileDAO.java size : 33
fileVisit File Name : fileSpring.java
isDirectory No : fileSpring.java size : 36
fileVisit File Name : fileTree.java
isDirectory No : fileTree.java size : 34
2. 파일 복사
Gradle에서 파일을 복사하기 위해서는 Copy태스크, Copy메소드를 이용 하면 된다
Copy태스크
- 파일 복사
- 파일 복사 시 파일명 수정 및 필터링하여 제어
- CopySpec 인터페이스를 구현
copy API 이용하기
copy {
from 'src/com/org/file' // 대상 파일의 경로
into 'src/com/des/file' // 목적지 경로
}
파일 경로 구조
앤트 패턴을 이용한 파일 복사
// 파일 복사
copy {
from 'src/com/org/file' // 대상 파일의 경로
into 'src/com/des/file' // 목적지 경로
include '**/*.java' // 포함
exclude '**/*Dao.java' // 제외
includeEmptyDirs = true // 빈 디렉터리도 복사 (기본값)
// includeEmptyDirs = false // 빈 디렉터리 제외
}
rename()을 이용한 파일 복사
파일명을 변경하고자 할 때 사용
copy {
from 'src/com/org/file' // 대상 파일의 경로
into 'src/com/des/file' // 목적지 경로
rename'originalTest.java','destination.java'
rename'(.*)Test.java','changeName.java'
// 정규표현식 사용 가능
}
rename()을 이용한 파일 복사
filter() 사용
copy {
//filter()를 이용한 파일 편집 및 복사
from('src/com/org/file'){
rename'original.java','editCloser.java'
}
into 'src/com/edit/file'
}
파일 내용 편집하여 복사
copy {
//filter()를 이용한 파일 편집 및 복사
from('src/com/org/file'){
// 복사 대상 디렉터리 지정
include '**/original.java'
// 어떤 파일을 지정할 지
rename 'original.java', 'editClose.java'
// 특정 파일명 변경
}
into 'src/com/edit/file'
// 목적지
// filter() 이용
filter { line ->
line.replaceAll'com.org.file','com.edit.file'
// com.org.file을 com.edit.file로 변경하여 복사
}
// filter() 이용
filter { line ->
line.replaceAll'original','editCloser'
}
}
지금까지는 copy API를 사용했다.
태스크를 이용한 파일 복사
//type에 copy를 지정해야 한다.
task copyTask(type: Copy){
// filter()를 이용한 파일 편집 및 복사
from('src/com/org/file'){
include'**/original.java'
rename 'original.java', 'editClose.java'
}
into 'src/com/edit/file'
// filter() 이용
filter { line ->
line.replaceAll'com.org.file','com.edit.file'
}
// filter() 이용
filter { line ->
line.replaceAll'original', 'editCloser'
}
}
copySpec 인터페이스를 이용한 파일 복사
def dataContent = copySpec {
from('src/com/org/file'){
include '**/original.java'
rename 'original.java','editCloser.java'
}
}
task fileCopy(type:Copy){
with dataContent
into 'build/target/back_up'
}
copySpec : from부분에서 디렉터리를 이용해서 파일을 지정할 수 있고 with 키워드를 사용하여
dataContent 부분을 참조하여 참조된 부분에 대해서 파일복사가 이루어짐
Task fileCopy : copySpec 인터페이스를 통해서 지정된 대상 파일들을 fileCopy를 통해서 복사를 수행가능
3. 파일 삭제
delete()를 이용한 파일 삭제
delete 'src/com/org/file/original.java','src/com/org/file/originalDao.java'
태스크의 type을 Delete로 지정하여 파일 삭제
task delFile(type : Delete) {
delete 'src/com/org/file/origianl.java','src/com/org/file/originalDao.java'
followSymlinks = true
}
'프로그래밍 공부 > Gradle' 카테고리의 다른 글
Gradle 테스트 자동화 환경 차이 제어, 패턴을 이용한 테스트, Junit, 병렬 테스트 (0) | 2021.09.08 |
---|---|
Gradle 의존관계 관리, 환경구성 정의, 저장소 정의 (0) | 2021.09.08 |
Gradle의 도메인 객체 Project, Task, Gradle, Settings, 기타 (0) | 2021.09.05 |
Gradle의 태스크(task) 10. Gradle의 태스크 그래프 (0) | 2021.09.03 |
Gradle의 스크립트 파일, Gradle 실습준비 eclipse IDE (0) | 2021.09.02 |