简体   繁体   English

如何获取Java中不带扩展名的文件名?

[英]How to get the filename without the extension in Java?

Can anyone tell me how to get the filename without the extension?谁能告诉我如何获取没有扩展名的文件名? Example:例子:

fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";

If you, like me, would rather use some library code where they probably have thought of all special cases, such as what happens if you pass in null or dots in the path but not in the filename, you can use the following:如果您像我一样,宁愿使用一些他们可能已经想到所有特殊情况的库代码,例如如果您在路径中传递null或点而不是在文件名中会发生什么,您可以使用以下内容:

import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);

The easiest way is to use a regular expression.最简单的方法是使用正则表达式。

fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");

The above expression will remove the last dot followed by one or more characters.上面的表达式将删除最后一个点后跟一个或多个字符。 Here's a basic unit test.这是一个基本的单元测试。

public void testRegex() {
    assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
    assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}

Here is the consolidated list order by my preference.这是我喜欢的综合列表顺序。

Using apache commons使用 Apache 公共资源

import org.apache.commons.io.FilenameUtils;

String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);
                          
                           OR

String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);

Using Google Guava (If u already using it)使用谷歌番石榴(如果你已经在使用它)

import com.google.common.io.Files;
String fileNameWithOutExt = Files.getNameWithoutExtension(fileName);

Files.getNameWithoutExtension Files.getNameWithoutExtension

Or using Core Java或者使用核心 Java

1) 1)

String fileName = file.getName();
int pos = fileName.lastIndexOf(".");
if (pos > 0 && pos < (fileName.length() - 1)) { // If '.' is not the first or last character.
    fileName = fileName.substring(0, pos);
}
if (fileName.indexOf(".") > 0) {
   return fileName.substring(0, fileName.lastIndexOf("."));
} else {
   return fileName;
}
private static final Pattern ext = Pattern.compile("(?<=.)\\.[^.]+$");

public static String getFileNameWithoutExtension(File file) {
    return ext.matcher(file.getName()).replaceAll("");
}

Liferay API Liferay API

import com.liferay.portal.kernel.util.FileUtil; 
String fileName = FileUtil.stripExtension(file.getName());

See the following test program:请参阅以下测试程序:

public class javatemp {
    static String stripExtension (String str) {
        // Handle null case specially.

        if (str == null) return null;

        // Get position of last '.'.

        int pos = str.lastIndexOf(".");

        // If there wasn't any '.' just return the string as is.

        if (pos == -1) return str;

        // Otherwise return the string, up to the dot.

        return str.substring(0, pos);
    }

    public static void main(String[] args) {
        System.out.println ("test.xml   -> " + stripExtension ("test.xml"));
        System.out.println ("test.2.xml -> " + stripExtension ("test.2.xml"));
        System.out.println ("test       -> " + stripExtension ("test"));
        System.out.println ("test.      -> " + stripExtension ("test."));
    }
}

which outputs:输出:

test.xml   -> test
test.2.xml -> test.2
test       -> test
test.      -> test

If your project uses Guava (14.0 or newer), you can go with Files.getNameWithoutExtension() .如果您的项目使用Guava (14.0 或更高版本),您可以使用Files.getNameWithoutExtension()

(Essentially the same as FilenameUtils.removeExtension() from Apache Commons IO, as the highest-voted answer suggests. Just wanted to point out Guava does this too. Personally I didn't want to add dependency to Commons—which I feel is a bit of a relic—just because of this.) (基本上与来自 Apache Commons IO 的FilenameUtils.removeExtension()相同,正如投票率最高的答案所暗示的那样。只是想指出 Guava 也这样做。就我个人而言,我不想添加对 Commons 的依赖——我觉得这是一个有点遗物——正因为如此。)

Below is reference from https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java以下是来自https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java的参考

/**
 * Gets the base name, without extension, of given file name.
 * <p/>
 * e.g. getBaseName("file.txt") will return "file"
 *
 * @param fileName
 * @return the base name
 */
public static String getBaseName(String fileName) {
    int index = fileName.lastIndexOf('.');
    if (index == -1) {
        return fileName;
    } else {
        return fileName.substring(0, index);
    }
}

If you don't like to import the full apache.commons, I've extracted the same functionality:如果您不喜欢导入完整的 apache.commons,我提取了相同的功能:

public class StringUtils {
    public static String getBaseName(String filename) {
        return removeExtension(getName(filename));
    }

    public static int indexOfLastSeparator(String filename) {
        if(filename == null) {
            return -1;
        } else {
            int lastUnixPos = filename.lastIndexOf(47);
            int lastWindowsPos = filename.lastIndexOf(92);
            return Math.max(lastUnixPos, lastWindowsPos);
        }
    }

    public static String getName(String filename) {
        if(filename == null) {
            return null;
        } else {
            int index = indexOfLastSeparator(filename);
            return filename.substring(index + 1);
        }
    }

    public static String removeExtension(String filename) {
        if(filename == null) {
            return null;
        } else {
            int index = indexOfExtension(filename);
            return index == -1?filename:filename.substring(0, index);
        }
    }

    public static int indexOfExtension(String filename) {
        if(filename == null) {
            return -1;
        } else {
            int extensionPos = filename.lastIndexOf(46);
            int lastSeparator = indexOfLastSeparator(filename);
            return lastSeparator > extensionPos?-1:extensionPos;
        }
    }
}

While I am a big believer in reusing libraries, the org.apache.commons.io JAR is 174KB, which is noticably large for a mobile app.虽然我非常相信重用库,但org.apache.commons.io JAR为 174KB,这对于移动应用程序来说非常大。

If you download the source code and take a look at their FilenameUtils class, you can see there are a lot of extra utilities, and it does cope with Windows and Unix paths, which is all lovely.如果您下载源代码并查看他们的 FilenameUtils 类,您会发现有很多额外的实用程序,它确实可以处理 Windows 和 Unix 路径,这一切都很可爱。

However, if you just want a couple of static utility methods for use with Unix style paths (with a "/" separator), you may find the code below useful.但是,如果您只想要几个用于 Unix 样式路径的静态实用程序方法(使用“/”分隔符),您可能会发现下面的代码很有用。

The removeExtension method preserves the rest of the path along with the filename. removeExtension方法将路径的其余部分与文件名一起保留。 There is also a similar getExtension .还有一个类似的getExtension

/**
 * Remove the file extension from a filename, that may include a path.
 * 
 * e.g. /path/to/myfile.jpg -> /path/to/myfile 
 */
public static String removeExtension(String filename) {
    if (filename == null) {
        return null;
    }

    int index = indexOfExtension(filename);

    if (index == -1) {
        return filename;
    } else {
        return filename.substring(0, index);
    }
}

/**
 * Return the file extension from a filename, including the "."
 * 
 * e.g. /path/to/myfile.jpg -> .jpg
 */
public static String getExtension(String filename) {
    if (filename == null) {
        return null;
    }

    int index = indexOfExtension(filename);

    if (index == -1) {
        return filename;
    } else {
        return filename.substring(index);
    }
}

private static final char EXTENSION_SEPARATOR = '.';
private static final char DIRECTORY_SEPARATOR = '/';

public static int indexOfExtension(String filename) {

    if (filename == null) {
        return -1;
    }

    // Check that no directory separator appears after the 
    // EXTENSION_SEPARATOR
    int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);

    int lastDirSeparator = filename.lastIndexOf(DIRECTORY_SEPARATOR);

    if (lastDirSeparator > extensionPos) {
        LogIt.w(FileSystemUtil.class, "A directory separator appears after the file extension, assuming there is no file extension");
        return -1;
    }

    return extensionPos;
}

对于 Kotlin,它现在很简单:

val fileNameStr = file.nameWithoutExtension

You can use java split function to split the filename from the extension, if you are sure there is only one dot in the filename which for extension.如果您确定文件名中只有一个点用于扩展名,您可以使用 java split 函数将文件名与扩展名分开。

File filename = new File('test.txt'); File.getName().split("[.]");

so the split[0] will return "test" and split[1] will return "txt"所以split[0]将返回“test”,而 split[1] 将返回“txt”

fileEntry.getName().substring(0, fileEntry.getName().lastIndexOf("."));

Given the String filename , you can do:给定 String filename ,您可以执行以下操作:

String filename = "test.xml";
filename.substring(0, filename.lastIndexOf("."));   // Output: test
filename.split("\\.")[0];   // Output: test
public static String getFileExtension(String fileName) {
        if (TextUtils.isEmpty(fileName) || !fileName.contains(".") || fileName.endsWith(".")) return null;
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static String getBaseFileName(String fileName) {
        if (TextUtils.isEmpty(fileName) || !fileName.contains(".") || fileName.endsWith(".")) return null;
        return fileName.substring(0,fileName.lastIndexOf("."));
    }

The fluent way:流畅的方式:

public static String fileNameWithOutExt (String fileName) {
    return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0)
            .filter(i-> i > fileName.lastIndexOf(File.separator))
            .map(i-> fileName.substring(0, i)).orElse(fileName);
}

从相对路径或完整路径获取名称的最简单方法是使用

import org.apache.commons.io.FilenameUtils; FilenameUtils.getBaseName(definitionFilePath)

You can split it by "."你可以用“。”来分割它。 and on index 0 is file name and on 1 is extension, but I would incline for the best solution with FileNameUtils from apache.commons-io like it was mentioned in the first article.并且索引 0 是文件名,索引 1 是扩展名,但我倾向于使用 apache.commons-io 中的 FileNameUtils 的最佳解决方案,就像第一篇文章中提到的那样。 It does not have to be removed, but sufficent is:它不必被删除,但足够的是:

String fileName = FilenameUtils.getBaseName("test.xml");

Use FilenameUtils.removeExtension from Apache Commons IO使用来自Apache Commons IOFilenameUtils.removeExtension

Example:例子:

You can provide full path name or only the file name .您可以提供完整的路径名仅提供文件名

String myString1 = FilenameUtils.removeExtension("helloworld.exe"); // returns "helloworld"
String myString2 = FilenameUtils.removeExtension("/home/abc/yey.xls"); // returns "yey"

Hope this helps ..希望这可以帮助 ..

Keeping it simple, use Java's String.replaceAll() method as follows:保持简单,使用 Java 的 String.replaceAll() 方法,如下所示:

String fileNameWithExt = "test.xml";
String fileNameWithoutExt
   = fileNameWithExt.replaceAll( "^.*?(([^/\\\\\\.]+))\\.[^\\.]+$", "$1" );

This also works when fileNameWithExt includes the fully qualified path.当 fileNameWithExt 包含完全限定的路径时,这也有效。

My solution needs the following import.我的解决方案需要以下导入。

import java.io.File;

The following method should return the desired output string:以下方法应返回所需的输出字符串:

private static String getFilenameWithoutExtension(File file) throws IOException {
    String filename = file.getCanonicalPath();
    String filenameWithoutExtension;
    if (filename.contains("."))
        filenameWithoutExtension = filename.substring(filename.lastIndexOf(System.getProperty("file.separator"))+1, filename.lastIndexOf('.'));
    else
        filenameWithoutExtension = filename.substring(filename.lastIndexOf(System.getProperty("file.separator"))+1);

    return filenameWithoutExtension;
}

com.google.common.io.Files com.google.common.io.Files

Files.getNameWithoutExtension(sourceFile.getName()) Files.getNameWithoutExtension(sourceFile.getName())

can do a job as well也可以做一份工作

file name only, where full path is also included.仅文件名,其中还包括完整路径。 No need for external libs, regex...etc不需要外部库、正则表达式等

    public class MyClass {
    public static void main(String args[]) {
  
  
      String file  = "some/long/directory/blah.x.y.z.m.xml";

      System.out.println(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf(".")));
     //outputs blah.x.y.z.m
    }

}

Try the code below.试试下面的代码。 Using core Java basic functions.使用核心 Java 基本功能。 It takes care of String s with extension, and without extension (without the '.' character).它处理带扩展名和不带扩展名的String (没有'.'字符)。 The case of multiple '.'多个'.'的情况is also covered.也被覆盖。

String str = "filename.xml";
if (!str.contains(".")) 
    System.out.println("File Name=" + str); 
else {
    str = str.substring(0, str.lastIndexOf("."));
    // Because extension is always after the last '.'
    System.out.println("File Name=" + str);
}

You can adapt it to work with null strings.您可以调整它以使用null字符串。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM