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

前端 未结 10 1029
-上瘾入骨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:24
    // Create an instance of a file (note the path is several levels deep)
    File file = new File('/tmp/whatever/certificate.crt')
    
    // To get the single fileName without the path (but with EXTENSION! so not answering the question of the author. Sorry for that...)
    String fileName = file.parentFile.toURI().relativize(file.toURI()).getPath()
    
    0 讨论(0)
  • 2020-12-14 15:25

    Simplest way is:

    'file.name.with.dots.tgz' - ~/\.\w+$/​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
    

    Result is:

    file.name.with.dots
    
    0 讨论(0)
  • 2020-12-14 15:27

    As mentioned in comments, where a filename ends & an extension begins depends on the situation. In my situation, I needed to get the basename (file without path, and without extension) of the following types of files: { foo.zip, bar/foo.tgz, foo.tar.gz } => all need to produce "foo" as the filename sans extension. (Most solutions, given foo.tar.gz would produce foo.tar.)

    Here's one (obvious) solution that will give you everything up to the first "."; optionally, you can get the entire extension either in pieces or (in this case) as a single remainder (splitting the filename into 2 parts). (Note: although unrelated to the task at hand, I'm also removing the path as well, by calling file.name.)

    file=new File("temp/foo.tar.gz")
    file.name.split("\\.", 2)[0]    // => return "foo" at [0], and "tar.gz" at [1]
    
    0 讨论(0)
  • 2020-12-14 15:30

    Maybe not as easy as you expected but working:

    new File("test").eachFile { 
      println it.name.lastIndexOf('.') >= 0 ? 
         it.name[0 .. it.name.lastIndexOf('.')-1] : 
         it.name 
      }
    
    0 讨论(0)
提交回复
热议问题