Java groovy 是否有一种简单的方法来获取没有扩展名的文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1569547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does groovy have an easy way to get a filename without the extension?
提问by Electrons_Ahoy
Say I have something like this:
说我有这样的事情:
new File("test").eachFile() { file->
println file.getName()
}
This prints the full filename of every file in the test
directory. Is there a Groovy way to get the filename without any extension? (Or am I back in regex land?)
这将打印test
目录中每个文件的完整文件名。有没有一种 Groovy 方法来获取没有任何扩展名的文件名?(或者我回到正则表达式领域?)
回答by Alexander Egger
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
}
回答by Alex
You can use regular expressions better. A function like the following would do the trick:
您可以更好地使用正则表达式。像下面这样的函数可以解决问题:
def getExtensionFromFilename(filename) {
def returned_value = ""
m = (filename =~ /(\.[^\.]*)$/)
if (m.size()>0) returned_value = ((m[0][0].size()>0) ? m[0][0].substring(1).trim().toLowerCase() : "");
return returned_value
}
回答by Nikita Volkov
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:
还有一个用于这种目的的 apache commons-io java lib,如果你使用 maven,你可以很容易地依赖它:
org.apache.commons.io.FilenameUtils.getBaseName(file.name)
回答by Mauro Zallocco
new File("test").eachFile() { file->
println file.getName().split("\.")[0]
}
This works well for file names like: foo, foo.bar
这适用于文件名,例如:foo, foo.bar
But if you have a file foo.bar.jar, then the above code prints out: foo If you want it to print out foo.bar instead, then the following code achieves that.
但是如果你有一个文件 foo.bar.jar,那么上面的代码会打印出: foo 如果你想让它打印出 foo.bar,那么下面的代码可以实现。
new File("test").eachFile() { file->
def names = (file.name.split("\.")
def name = names.size() > 1 ? (names - names[-1]).join('.') : names[0]
println name
}
回答by michael
As mentioned in comments, where a filename ends & an extension begins depends on the situation. In mysituation, I needed to get the basename (file without path, andwithout 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
.)
正如评论中提到的,文件名的结尾和扩展名的开头取决于具体情况。在我的情况下,我需要获取以下类型文件的基本名称(没有路径和扩展名的文件): { foo.zip
, bar/foo.tgz
, foo.tar.gz
} => 都需要生成“ foo
”作为文件名无扩展名。(给定的大多数解决方案foo.tar.gz
都会产生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
.)
这是一个(明显的)解决方案,它将为您提供第一个“。”之前的所有内容;可选地,您可以将整个扩展名分成2
几部分或(在这种情况下)作为单个余数(将文件名分成几部分)。(注意:虽然与手头的任务无关,但我也通过调用删除了路径file.name
。)
file=new File("temp/foo.tar.gz")
file.name.split("\.", 2)[0] // => return "foo" at [0], and "tar.gz" at [1]
回答by Jay P.
The FilenameUtils class, which is part of the apache commons io package, has a robust solution. Example usage:
FilenameUtils 类是 apache commons io 包的一部分,有一个强大的解决方案。用法示例:
import org.apache.commons.io.FilenameUtils
String filename = '/tmp/hello-world.txt'
def fileWithoutExt = FilenameUtils.removeExtension(filename)
This isn't the groovy way, but might be helpful if you need to support lots of edge cases.
这不是常规方式,但如果您需要支持大量边缘情况,可能会有所帮助。
回答by Sajumon Joseph
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
以下某些解决方案(使用 apache 库的解决方案除外)不适用于此示例 - c:/test.me/firstfile
If I try to find an extension for above entry, I will get ".me/firstfile" - :(
如果我尝试为上述条目找到扩展名,我将得到“.me/firstfile” - :(
Better approach will be to find the last occurrence of File.separator if present and then look for filename or extension.
更好的方法是找到最后一次出现的 File.separator(如果存在),然后查找文件名或扩展名。
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:
注意:(下面有一个小技巧。对于Windows,文件分隔符是\。但这是正则表达式中的特殊字符,因此当我们在正则表达式中使用包含File.separator的变量时,我必须转义这就是我这样做的原因:
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/dddd/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"
回答by Pier
The cleanest way.
最干净的方式。
String fileWithoutExt = file.name.take(file.name.lastIndexOf('.'))
String fileWithoutExt = file.name.take(file.name.lastIndexOf('.'))
回答by librucha
Simplest way is:
最简单的方法是:
'file.name.with.dots.tgz' - ~/\.\w+$/????????????????????????????????????
Result is:
结果是:
file.name.with.dots
回答by Marco
// 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()