简体   繁体   English

groovy 是否有一种简单的方法来获取没有扩展名的文件名?

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

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.这将打印test目录中每个文件的完整文件名。 Is there a Groovy way to get the filename without any extension?有没有一种 Groovy 方法来获取没有任何扩展名的文件名? (Or am I back in regex land?) (或者我回到正则表达式领域?)

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)

最干净的方式。

String fileWithoutExt = file.name.take(file.name.lastIndexOf('.'))

Simplest way is:最简单的方法是:

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

Result is:结果是:

file.name.with.dots
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
}

The FilenameUtils class, which is part of the apache commons io package, has a robust solution. FilenameUtils 类是 apache commons io 包的一部分,有一个强大的解决方案。 Example usage:用法示例:

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.这不是常规方式,但如果您需要支持大量边缘情况,可能会有所帮助。

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 
  }

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.我的情况下,我需要获取以下类型文件的基本名称(没有路径扩展名的文件):{ foo.zip , bar/foo.tgz , foo.tar.gz } => all need to foo.tar.gz " foo " 作为文件名无扩展名。 (Most solutions, given foo.tar.gz would produce foo.tar .) (大多数解决方案,给定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).可选地,您可以将整个扩展名分成几部分或(在这种情况下)作为单个余数(将文件名分成2部分)。 (Note: although unrelated to the task at hand, I'm also removing the path as well, by calling file.name .) (注意:虽然与手头的任务无关,但我也通过调用file.name删除了路径。)

file=new File("temp/foo.tar.gz")
file.name.split("\\.", 2)[0]    // => return "foo" at [0], and "tar.gz" at [1]

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
}

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"
// 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取Java中不带扩展名的文件名? - How to get the filename without the extension in Java? 正则表达式从路径获取带或不带扩展名的文件名 - Regex to get filename with or without extension from a path Hadoop:在没有可写接口的情况下将对象作为输出值的简便方法 - Hadoop: Easy way to have object as output value without Writable interface Java:当我有一组对象时,有没有一种简单的方法来获得平均值? - Java: Is there an easy way to get an average when I have a collection of objects? 有没有一种简单的方法可以从键盘上获取字符而无需在Java中按Enter键? - Is there an easy way to get characters from the keyboard without hitting enter in Java? groovy是否有日期文字? - Does groovy have date literals? 有没有办法替换groovy / java中的类扩展? - Is there a way to replace class extension in groovy/java? 根据扩展名Java获取某些FileName - Get certain FileName based on its extension Java @RestController 有没有办法在没有 Servlet 和 HttpServletRequest 的情况下做过滤器或拦截器? - Does @RestController have a way to do filter or interceptor without Servlet and HttpServletRequest? 在Spring控制器中获取参数的简便方法? - Easy way to get parameters in Spring controller?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM