首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Java中获取不带扩展名的文件名?

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

Stack Overflow用户
提问于 2009-05-29 12:31:40
回答 17查看 332.3K关注 0票数 308

谁能告诉我如何获得不带扩展名的文件名?示例:

代码语言:javascript
复制
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
EN

回答 17

Stack Overflow用户

发布于 2009-05-29 05:31:42

最简单的方法是使用正则表达式。

代码语言:javascript
复制
fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");

上面的表达式将删除后面跟着一个或多个字符的最后一个点。这是一个基本的单元测试。

代码语言:javascript
复制
public void testRegex() {
    assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
    assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}
票数 173
EN

Stack Overflow用户

发布于 2009-05-29 05:27:24

请参阅以下测试程序:

代码语言:javascript
复制
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."));
    }
}

以下哪项输出:

代码语言:javascript
复制
test.xml   -> test
test.2.xml -> test.2
test       -> test
test.      -> test
票数 56
EN

Stack Overflow用户

发布于 2016-07-04 11:36:17

下面是来自https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java的参考资料

代码语言:javascript
复制
/**
 * 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);
    }
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/924394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档