Say I have something like this:
new File(\"test\").eachFile() { file->
println file.getName()
}
This prints the full filename of eve
// 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()
Simplest way is:
'file.name.with.dots.tgz' - ~/\.\w+$/
Result is:
file.name.with.dots
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]
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
}