如何在 Java 中从字符串中删除文件扩展名?

发布于 2024-07-23 05:05:47 字数 121 浏览 6 评论 0原文

在Java中修剪后缀最有效的方法是什么,如下所示:

title part1.txt
title part2.html
=>
title part1
title part2

What's the most efficient way to trim the suffix in Java, like this:

title part1.txt
title part2.html
=>
title part1
title part2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

对不⑦ 2024-07-30 05:05:48

伙计们,不要给心灵带来压力。 我已经做过很多次了。 只需将此公共静态方法复制粘贴到您的 staticUtils 库中以供将来使用;-)

static String removeExtension(String path){
        String filename;
        String foldrpath;
        String filenameWithoutExtension;
        if(path.equals("")){return "";}
        if(path.contains("\\")){    // direct substring method give wrong result for "a.b.c.d\e.f.g\supersu"
            filename = path.substring(path.lastIndexOf("\\"));
            foldrpath = path.substring(0, path.lastIndexOf('\\'));;
            if(filename.contains(".")){
                filenameWithoutExtension = filename.substring(0, filename.lastIndexOf('.'));
            }else{
                filenameWithoutExtension = filename;
            }
            return foldrpath + filenameWithoutExtension;
        }else{
            return path.substring(0, path.lastIndexOf('.'));
        }
    }

dont do stress on mind guys. i did already many times. just copy paste this public static method in your staticUtils library for future uses ;-)

static String removeExtension(String path){
        String filename;
        String foldrpath;
        String filenameWithoutExtension;
        if(path.equals("")){return "";}
        if(path.contains("\\")){    // direct substring method give wrong result for "a.b.c.d\e.f.g\supersu"
            filename = path.substring(path.lastIndexOf("\\"));
            foldrpath = path.substring(0, path.lastIndexOf('\\'));;
            if(filename.contains(".")){
                filenameWithoutExtension = filename.substring(0, filename.lastIndexOf('.'));
            }else{
                filenameWithoutExtension = filename;
            }
            return foldrpath + filenameWithoutExtension;
        }else{
            return path.substring(0, path.lastIndexOf('.'));
        }
    }
熟人话多 2024-07-30 05:05:48

我会这样做:

String title_part = "title part1.txt";
int i;
for(i=title_part.length()-1 ; i>=0 && title_part.charAt(i)!='.' ; i--);
title_part = title_part.substring(0,i);

从开始到结束直到“。” 然后调用子串。

编辑:
可能不是高尔夫,但它很有效:)

I would do like this:

String title_part = "title part1.txt";
int i;
for(i=title_part.length()-1 ; i>=0 && title_part.charAt(i)!='.' ; i--);
title_part = title_part.substring(0,i);

Starting to the end till the '.' then call substring.

Edit:
Might not be a golf but it's effective :)

岁月静好 2024-07-30 05:05:48

请记住没有文件扩展名或有多个文件扩展名的情况

示例文件名:文件| 文件.txt | 文件.tar.bz2

/**
 *
 * @param fileName
 * @return file extension
 * example file.fastq.gz => fastq.gz
 */
private String extractFileExtension(String fileName) {
    String type = "undefined";
    if (FilenameUtils.indexOfExtension(fileName) != -1) {
        String fileBaseName = FilenameUtils.getBaseName(fileName);
        int indexOfExtension = -1;
        while (fileBaseName.contains(".")) {
            indexOfExtension = FilenameUtils.indexOfExtension(fileBaseName);
            fileBaseName = FilenameUtils.getBaseName(fileBaseName);
        }
        type = fileName.substring(indexOfExtension + 1, fileName.length());
    }
    return type;
}

Keeping in mind the scenarios where there is no file extension or there is more than one file extension

example Filename : file | file.txt | file.tar.bz2

/**
 *
 * @param fileName
 * @return file extension
 * example file.fastq.gz => fastq.gz
 */
private String extractFileExtension(String fileName) {
    String type = "undefined";
    if (FilenameUtils.indexOfExtension(fileName) != -1) {
        String fileBaseName = FilenameUtils.getBaseName(fileName);
        int indexOfExtension = -1;
        while (fileBaseName.contains(".")) {
            indexOfExtension = FilenameUtils.indexOfExtension(fileBaseName);
            fileBaseName = FilenameUtils.getBaseName(fileBaseName);
        }
        type = fileName.substring(indexOfExtension + 1, fileName.length());
    }
    return type;
}
小兔几 2024-07-30 05:05:48
String img = "example.jpg";
// String imgLink = "http://www.example.com/example.jpg";
URI uri = null;

try {
    uri = new URI(img);
    String[] segments = uri.getPath().split("/");
    System.out.println(segments[segments.length-1].split("\\.")[0]);
} catch (Exception e) {
    e.printStackTrace();
}

这将为 imgimgLink 输出 example

String img = "example.jpg";
// String imgLink = "http://www.example.com/example.jpg";
URI uri = null;

try {
    uri = new URI(img);
    String[] segments = uri.getPath().split("/");
    System.out.println(segments[segments.length-1].split("\\.")[0]);
} catch (Exception e) {
    e.printStackTrace();
}

This will output example for both img and imgLink

小ぇ时光︴ 2024-07-30 05:05:48
private String trimFileName(String fileName)
    {
        String[] ext;
        ext = fileName.split("\\.");
        
        return fileName.replace(ext[ext.length - 1], "");

    }

此代码会将文件名分成包含“.”的部分,例如 如果文件名是file-name.hello.txt,那么它将被分解为字符串数组,{“file-name”,“hello”,“txt”}。 所以无论如何,这个字符串数组中的最后一个元素将是该特定文件的文件扩展名,因此我们可以简单地使用 arrayname.length - 1 找到任何数组的最后一个元素,所以在我们了解之后最后一个元素,我们可以将文件扩展名替换为该文件名中的空字符串。 最后将返回 file-name.hello。 ,如果您还想删除最后一个句点,则可以将仅包含句点的字符串添加到返回行中字符串数组的最后一个元素。 看起来应该是这样的,

return fileName.replace("." +  ext[ext.length - 1], "");
private String trimFileName(String fileName)
    {
        String[] ext;
        ext = fileName.split("\\.");
        
        return fileName.replace(ext[ext.length - 1], "");

    }

This code will spilt the file name into parts where ever it has " . ", For eg. If the file name is file-name.hello.txt then it will be spilted into string array as , { "file-name", "hello", "txt" }. So anyhow the last element in this string array will be the file extension of that particular file , so we can simply find the last element of any arrays with arrayname.length - 1, so after we get to know the last element, we can just replace the file extension with an empty string in that file name. Finally this will return file-name.hello. , if you want to remove also the last period then you can add the string with only period to the last element of string array in the return line. Which should look like,

return fileName.replace("." +  ext[ext.length - 1], "");
趁微风不噪 2024-07-30 05:05:48
public static String removeExtension(String file) {
    if(file != null && file.length() > 0) {
        while(file.contains(".")) {
            file = file.substring(0, file.lastIndexOf('.'));
        }
    }
    return file;
}
public static String removeExtension(String file) {
    if(file != null && file.length() > 0) {
        while(file.contains(".")) {
            file = file.substring(0, file.lastIndexOf('.'));
        }
    }
    return file;
}
深居我梦 2024-07-30 05:05:47

这是我们不应该自己编写的代码。 使用图书馆来处理平凡的事情,节省你的大脑来处理困难的事情。

在这种情况下,我建议使用 FilenameUtils.removeExtension() 来自 Apache Commons IO< /a>

This is the sort of code that we shouldn't be doing ourselves. Use libraries for the mundane stuff, save your brain for the hard stuff.

In this case, I recommend using FilenameUtils.removeExtension() from Apache Commons IO

霓裳挽歌倾城醉 2024-07-30 05:05:47
str.substring(0, str.lastIndexOf('.'))
str.substring(0, str.lastIndexOf('.'))
橘虞初梦 2024-07-30 05:05:47

虽然在一行中使用 String.substringString.lastIndex 很好,但在处理某些文件路径方面存在一些问题。

以以下路径为例:

a.b/c

使用单行将导致:

a

这是不正确的。

结果应该是 c,但由于文件缺少扩展名,但路径中有一个名称中带有 . 的目录,单行方法被欺骗了将部分路径作为文件名,这是不正确的。

需要检查

灵感来自skaffman的回答,我看了一下Apache Commons IO

为了重新创建它的行为,我编写了一些新方法应该满足的测试,如下所示:(

Path                  Filename
--------------        --------
a/b/c                 c
a/b/c.jpg             c
a/b/c.jpg.jpg         c.jpg

a.b/c                 c
a.b/c.jpg             c
a.b/c.jpg.jpg         c.jpg

c                     c
c.jpg                 c
c.jpg.jpg             c.jpg

这就是我检查过的所有内容 - 可能还有其他检查应该到位,但我忽略了。 )

实现

以下是我对 removeExtension 方法的实现:

public static String removeExtension(String s) {

    String separator = System.getProperty("file.separator");
    String filename;

    // Remove the path upto the filename.
    int lastSeparatorIndex = s.lastIndexOf(separator);
    if (lastSeparatorIndex == -1) {
        filename = s;
    } else {
        filename = s.substring(lastSeparatorIndex + 1);
    }

    // Remove the extension.
    int extensionIndex = filename.lastIndexOf(".");
    if (extensionIndex == -1)
        return filename;

    return filename.substring(0, extensionIndex);
}

通过上述测试运行此 removeExtension 方法会产生上面列出的结果。

使用以下代码对该方法进行了测试。 由于这是在 Windows 上运行的,因此路径分隔符是 \,当用作 String 文字的一部分时,必须使用 \ 进行转义。

System.out.println(removeExtension("a\\b\\c"));
System.out.println(removeExtension("a\\b\\c.jpg"));
System.out.println(removeExtension("a\\b\\c.jpg.jpg"));

System.out.println(removeExtension("a.b\\c"));
System.out.println(removeExtension("a.b\\c.jpg"));
System.out.println(removeExtension("a.b\\c.jpg.jpg"));

System.out.println(removeExtension("c"));
System.out.println(removeExtension("c.jpg"));
System.out.println(removeExtension("c.jpg.jpg"));

结果是:

c
c
c.jpg
c
c
c.jpg
c
c
c.jpg

结果是方法应满足的测试中概述的期望结果。

As using the String.substring and String.lastIndex in a one-liner is good, there are some issues in terms of being able to cope with certain file paths.

Take for example the following path:

a.b/c

Using the one-liner will result in:

a

That's incorrect.

The result should have been c, but since the file lacked an extension, but the path had a directory with a . in the name, the one-liner method was tricked into giving part of the path as the filename, which is not correct.

Need for checks

Inspired by skaffman's answer, I took a look at the FilenameUtils.removeExtension method of the Apache Commons IO.

In order to recreate its behavior, I wrote a few tests the new method should fulfill, which are the following:

Path                  Filename
--------------        --------
a/b/c                 c
a/b/c.jpg             c
a/b/c.jpg.jpg         c.jpg

a.b/c                 c
a.b/c.jpg             c
a.b/c.jpg.jpg         c.jpg

c                     c
c.jpg                 c
c.jpg.jpg             c.jpg

(And that's all I've checked for -- there probably are other checks that should be in place that I've overlooked.)

The implementation

The following is my implementation for the removeExtension method:

public static String removeExtension(String s) {

    String separator = System.getProperty("file.separator");
    String filename;

    // Remove the path upto the filename.
    int lastSeparatorIndex = s.lastIndexOf(separator);
    if (lastSeparatorIndex == -1) {
        filename = s;
    } else {
        filename = s.substring(lastSeparatorIndex + 1);
    }

    // Remove the extension.
    int extensionIndex = filename.lastIndexOf(".");
    if (extensionIndex == -1)
        return filename;

    return filename.substring(0, extensionIndex);
}

Running this removeExtension method with the above tests yield the results listed above.

The method was tested with the following code. As this was run on Windows, the path separator is a \ which must be escaped with a \ when used as part of a String literal.

System.out.println(removeExtension("a\\b\\c"));
System.out.println(removeExtension("a\\b\\c.jpg"));
System.out.println(removeExtension("a\\b\\c.jpg.jpg"));

System.out.println(removeExtension("a.b\\c"));
System.out.println(removeExtension("a.b\\c.jpg"));
System.out.println(removeExtension("a.b\\c.jpg.jpg"));

System.out.println(removeExtension("c"));
System.out.println(removeExtension("c.jpg"));
System.out.println(removeExtension("c.jpg.jpg"));

The results were:

c
c
c.jpg
c
c
c.jpg
c
c
c.jpg

The results are the desired results outlined in the test the method should fulfill.

迷迭香的记忆 2024-07-30 05:05:47
String foo = "title part1.txt";
foo = foo.substring(0, foo.lastIndexOf('.'));
String foo = "title part1.txt";
foo = foo.substring(0, foo.lastIndexOf('.'));
幸福还没到 2024-07-30 05:05:47

顺便说一句,就我而言,当我想要一个快速解决方案来删除特定扩展时,这大约是我所做的:

  if (filename.endsWith(ext))
    return filename.substring(0,filename.length() - ext.length());
  else
    return filename;

BTW, in my case, when I wanted a quick solution to remove a specific extension, this is approximately what I did:

  if (filename.endsWith(ext))
    return filename.substring(0,filename.length() - ext.length());
  else
    return filename;
So尛奶瓶 2024-07-30 05:05:47

如果您的项目已经依赖于 Google 核心库,请使用 com.google.common.io.Files 类中的方法。 您需要的方法是getNameWithoutExtension

Use a method in com.google.common.io.Files class if your project is already dependent on Google core library. The method you need is getNameWithoutExtension.

话少心凉 2024-07-30 05:05:47

你可以试试这个功能,很基础

public String getWithoutExtension(String fileFullPath){
    return fileFullPath.substring(0, fileFullPath.lastIndexOf('.'));
}

you can try this function , very basic

public String getWithoutExtension(String fileFullPath){
    return fileFullPath.substring(0, fileFullPath.lastIndexOf('.'));
}
吃素的狼 2024-07-30 05:05:47
String fileName="foo.bar";
int dotIndex=fileName.lastIndexOf('.');
if(dotIndex>=0) { // to prevent exception if there is no dot
  fileName=fileName.substring(0,dotIndex);
}

这是一个技巧问题吗? :p

我想不出更快的 ATM 方式。

String fileName="foo.bar";
int dotIndex=fileName.lastIndexOf('.');
if(dotIndex>=0) { // to prevent exception if there is no dot
  fileName=fileName.substring(0,dotIndex);
}

Is this a trick question? :p

I can't think of a faster way atm.

回忆凄美了谁 2024-07-30 05:05:47

我找到了 coolbird 的答案特别有用。

但我将最后一个结果语句更改为:

if (extensionIndex == -1)
  return s;

return s.substring(0, lastSeparatorIndex+1) 
         + filename.substring(0, extensionIndex);

因为我希望返回完整路径名。

So "C:\Users\mroh004.COM\Documents\Test\Test.xml" becomes 
   "C:\Users\mroh004.COM\Documents\Test\Test" and not
   "Test"

I found coolbird's answer particularly useful.

But I changed the last result statements to:

if (extensionIndex == -1)
  return s;

return s.substring(0, lastSeparatorIndex+1) 
         + filename.substring(0, extensionIndex);

as I wanted the full path name to be returned.

So "C:\Users\mroh004.COM\Documents\Test\Test.xml" becomes 
   "C:\Users\mroh004.COM\Documents\Test\Test" and not
   "Test"
七七 2024-07-30 05:05:47
filename.substring(filename.lastIndexOf('.'), filename.length()).toLowerCase();
filename.substring(filename.lastIndexOf('.'), filename.length()).toLowerCase();
舟遥客 2024-07-30 05:05:47

使用正则表达式。 这个点取代了最后一个点,以及它后面的所有内容。

String baseName = fileName.replaceAll("\\.[^.]*$", "");

如果您想预编译正则表达式,您还可以创建一个 Pattern 对象。

Use a regex. This one replaces the last dot, and everything after it.

String baseName = fileName.replaceAll("\\.[^.]*$", "");

You can also create a Pattern object if you want to precompile the regex.

鸵鸟症 2024-07-30 05:05:47

如果你使用 Spring 你可以使用

org.springframework.util.StringUtils.stripFilenameExtension(String path)

从给定的 Java 资源路径中去除文件扩展名,例如

“mypath/myfile.txt”-> “我的路径/我的文件”。

参数:path – 文件路径

返回:去掉文件扩展名的路径

If you use Spring you could use

org.springframework.util.StringUtils.stripFilenameExtension(String path)

Strip the filename extension from the given Java resource path, e.g.

"mypath/myfile.txt" -> "mypath/myfile".

Params: path – the file path

Returns: the path with stripped filename extension

姜生凉生 2024-07-30 05:05:47
 private String trimFileExtension(String fileName)
  {
     String[] splits = fileName.split( "\\." );
     return StringUtils.remove( fileName, "." + splits[splits.length - 1] );
  }
 private String trimFileExtension(String fileName)
  {
     String[] splits = fileName.split( "\\." );
     return StringUtils.remove( fileName, "." + splits[splits.length - 1] );
  }
山色无中 2024-07-30 05:05:47
String[] splitted = fileName.split(".");
String fileNameWithoutExtension = fileName.replace("." + splitted[splitted.length - 1], "");
String[] splitted = fileName.split(".");
String fileNameWithoutExtension = fileName.replace("." + splitted[splitted.length - 1], "");
樱桃奶球 2024-07-30 05:05:47

使用字符串图像路径创建一个新文件

String imagePath;
File test = new File(imagePath);
test.getName();
test.getPath();
getExtension(test.getName());


public static String getExtension(String uri) {
        if (uri == null) {
            return null;
        }

        int dot = uri.lastIndexOf(".");
        if (dot >= 0) {
            return uri.substring(dot);
        } else {
            // No extension.
            return "";
        }
    }

create a new file with string image path

String imagePath;
File test = new File(imagePath);
test.getName();
test.getPath();
getExtension(test.getName());


public static String getExtension(String uri) {
        if (uri == null) {
            return null;
        }

        int dot = uri.lastIndexOf(".");
        if (dot >= 0) {
            return uri.substring(dot);
        } else {
            // No extension.
            return "";
        }
    }
Smile简单爱 2024-07-30 05:05:47

org.apache.commons.io.FilenameUtils 版本 2.4 给出了以下答案

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);
    }
}

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

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

public static final char EXTENSION_SEPARATOR = '.';
private static final char UNIX_SEPARATOR = '/';
private static final char WINDOWS_SEPARATOR = '\\';

org.apache.commons.io.FilenameUtils version 2.4 gives the following answer

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);
    }
}

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

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

public static final char EXTENSION_SEPARATOR = '.';
private static final char UNIX_SEPARATOR = '/';
private static final char WINDOWS_SEPARATOR = '\\';
太傻旳人生 2024-07-30 05:05:47

我能写的最好的尝试坚持 Path 类:

Path removeExtension(Path path) {
    return path.resolveSibling(path.getFileName().toString().replaceFirst("\\.[^.]*$", ""));
}

The best what I can write trying to stick to the Path class:

Path removeExtension(Path path) {
    return path.resolveSibling(path.getFileName().toString().replaceFirst("\\.[^.]*
quot;, ""));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文