Does groovy have an easy way to get a filename without the extension?

前端 未结 10 1097
-上瘾入骨i
-上瘾入骨i 2020-12-14 14:41

Say I have something like this:

new File(\"test\").eachFile() { file->  
println file.getName()  
}

This prints the full filename of eve

10条回答
  •  难免孤独
    2020-12-14 15:10

    Note

    import java.io.File;
    
    def fileNames    = [ "/a/b.c/first.txt", 
                         "/b/c/second",
                         "c:\\a\\b.c\\third...",
                         "c:\\a\b\\c\\.text"
                       ]
    
    def fileSeparator = "";
    
    fileNames.each { 
        // You can keep the below code outside of this loop. Since my example
        // contains both windows and unix file structure, I am doing this inside the loop.
        fileSeparator= "\\" + File.separator;
        if (!it.contains(File.separator)) {
            fileSeparator    =  "\\/"
        }
    
        println "File extension is : ${it.find(/((?<=\.)[^\.${fileSeparator}]+)$/)}"
        it    =  it.replaceAll(/(\.([^\.${fileSeparator}]+)?)$/,"")
    
        println "Filename is ${it}" 
    }
    

    Some of the below solutions (except the one using apache library) doesn't work for this example - c:/test.me/firstfile

    If I try to find an extension for above entry, I will get ".me/firstfile" - :(

    Better approach will be to find the last occurrence of File.separator if present and then look for filename or extension.

    Note: (There is a little trick happens below. For Windows, the file separator is \. But this is a special character in regular expression and so when we use a variable containing the File.separator in the regular expression, I have to escape it. That is why I do this:

    def fileSeparator= "\\" + File.separator;
    

    Hope it makes sense :)

    Try this out:

    import java.io.File;
    
    String strFilename     =  "C:\\first.1\\second.txt";
    // Few other flavors 
    // strFilename = "/dd/ffffdd/2.dd/dio/dkljlds.dd"
    
    def fileSeparator= "\\" + File.separator;
    if (!strFilename.contains(File.separator)) {
        fileSeparator    =  "\\/"
    }
    
    def fileExtension = "";
    (strFilename    =~ /((?<=\.)[^\.${fileSeparator}]+)$/).each { match,  extension -> fileExtension = extension }
    println "Extension is:$fileExtension"
    

提交回复
热议问题