题目:
假设有文件夹SRC存有编译之前的源文件, 文件夹DIST存有编译之后的二进制文件.
编译前和编译后的文件名相同, 但扩展名不同.
如果编译失败, 在DIST中就不会生成对应的二进制文件.
比如, AAA.fmb 编译之后是 AAA.fmx,
又如, BBB.rdf 编译之后是 BBB.rep,
又如, CCC.plx 编译之后是 CCC.pll.
现在的问题是, 在通过 ANT 脚本进行编译之后, DIST中的文件数 少于 SRC中的文件数.
请通过编程的方式对比SRC和DIST文件夹, 找出编译失败的文件.
解答 by Groovy:
def dirA = new File("G:\\CODE\\TEST\\A").listFiles();
def dirB = new File("G:\\CODE\\TEST\\B").listFiles();
def listA = new ArrayList()
def listB = new ArrayList()
dirA.each{it->
listA.add(it.name.replaceFirst(~/\.[^\.]+$/, ''))
}
dirB.each{it->
listB.add(it.name.replaceFirst(~/\.[^\.]+$/, ''))
}
//println listA
//println listB
listA.each{it->
if(!listB.contains(it)){
println(it)
}
}
如何用JAVA取得不带扩展名的文件名?
//The easiest way is to use a regular expression.
fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");
//The above expression will remove the last dot followed by one or more characters.
//Here's a basic unit test.
public void testRegex() {
assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}
如何用GROOVY取得不带扩展名的文件名?
//I believe the grooviest way would be:
file.name.lastIndexOf('.').with {it != -1 ? file.name[0..<it] : file.name}
//or with a simple regexp:
file.name.replaceFirst(~/\.[^\.]+$/, '')
//also there's an apache commons-io java lib for that kinda purposes,
//which you could easily depend on if you use maven:
org.apache.commons.io.FilenameUtils.getBaseName(file.name)