提问人:longda 提问时间:8/26/2010 最后编辑:longda 更新时间:11/4/2022 访问量:849134
如何在 Java 中获取文件的文件扩展名?
How do I get the file extension of a file in Java?
问:
需要明确的是,我不是在寻找MIME类型。
假设我有以下输入:/path/to/file/foo.txt
我想要一种方法来分解这个输入,特别是用于扩展。Java 中是否有任何内置方法可以做到这一点?我想避免编写自己的解析器。.txt
答:
你真的需要一个“解析器”吗?
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i+1);
}
假设您正在处理简单的类似 Windows 的文件名,而不是类似 .archive.tar.gz
顺便说一句,如果目录可能有“.”,但文件名本身没有(如),您可以这样做/path/to.a/file
String extension = "";
int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
if (i > p) {
extension = fileName.substring(i+1);
}
评论
i > 0
i >= 0
i != -1
.htaccess
// Modified from EboMike's answer
String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));
扩展在运行时应该有“.txt”。
评论
JFileChooser怎么样?这并不简单,因为您需要解析其最终输出......
JFileChooser filechooser = new JFileChooser();
File file = new File("your.txt");
System.out.println("the extension type:"+filechooser.getTypeDescription(file));
这是一个MIME类型...
还行。。。我忘了你不想知道它的MIME类型。
以下链接中的有趣代码:http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
/*
* Get the extension of a file.
*/
public static String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i+1).toLowerCase();
}
return ext;
}
相关问题:如何在 Java 中从 String 修剪文件扩展名?
怎么样(使用 Java 1.5 正则表达式):
String[] split = fullFileName.split("\\.");
String ext = split[split.length - 1];
如果您使用 Guava 库,您可以求助于文件
实用程序类。它有一个特定的方法,getFileExtension()。
例如:
String path = "c:/path/to/file/foo.txt";
String ext = Files.getFileExtension(path);
System.out.println(ext); //prints txt
此外,您还可以使用类似的函数 getNameWithoutExtension() 获取文件名:
String filename = Files.getNameWithoutExtension(path);
System.out.println(filename); //prints foo
评论
getFileExtension
int dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1)
Files
下面是一个正确处理的方法,即使在目录名称中带有点的路径中也是如此:.tar.gz
private static final String getExtension(final String filename) {
if (filename == null) return null;
final String afterLastSlash = filename.substring(filename.lastIndexOf('/') + 1);
final int afterLastBackslash = afterLastSlash.lastIndexOf('\\') + 1;
final int dotIndex = afterLastSlash.indexOf('.', afterLastBackslash);
return (dotIndex == -1) ? "" : afterLastSlash.substring(dotIndex + 1);
}
afterLastSlash
创建是为了加快查找速度,因为如果其中有一些斜杠,则不必搜索整个字符串。afterLastBackslash
原来的内部是重用的,没有添加任何垃圾,JVM 可能会注意到 afterLastSlash
立即成为垃圾,以便将其放在堆栈而不是堆上。char[]
String
评论
getExtension
"my zip. don't touch.tar.gz"
在这种情况下,请使用 Apache Commons IO 中的 FilenameUtils.getExtension
以下是如何使用它的示例(您可以指定完整路径或仅指定文件名):
import org.apache.commons.io.FilenameUtils;
// ...
String ext1 = FilenameUtils.getExtension("/path/to/file/foo.txt"); // returns "txt"
String ext2 = FilenameUtils.getExtension("bar.exe"); // returns "exe"
Maven 依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
Gradle Groovy DSL
implementation 'commons-io:commons-io:2.6'
Gradle Kotlin DSL
implementation("commons-io:commons-io:2.6")
其他人 https://search.maven.org/artifact/commons-io/commons-io/2.6/jar
评论
只是一个基于正则表达式的替代方案。没那么快,没那么好。
Pattern pattern = Pattern.compile("\\.([^.]*)$");
Matcher matcher = pattern.matcher(fileName);
if (matcher.find()) {
String ext = matcher.group(1);
}
为了考虑点前没有字符的文件名,您必须使用已接受答案的细微变化:
String extension = "";
int i = fileName.lastIndexOf('.');
if (i >= 0) {
extension = fileName.substring(i+1);
}
"file.doc" => "doc"
"file.doc.gz" => "gz"
".doc" => "doc"
评论
private String getFileExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf(".");
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf);
}
评论
我的肮脏和可能最小的使用 String.replaceAll:
.replaceAll("^.*\\.(.*)$", "$1")
请注意,首先是贪婪的,因此它会尽可能地抓取大多数可能的字符,然后只剩下最后一个点和文件扩展名。*
评论
.replaceAll(".*\\.", "")
如果你打算使用Apache commons-io,并且只想检查文件的扩展名然后做一些操作,你可以使用它,这里有一个片段:
if(FilenameUtils.isExtension(file.getName(),"java")) {
someoperation();
}
评论
如果在 Android 上,您可以使用以下功能:
String ext = android.webkit.MimeTypeMap.getFileExtensionFromUrl(file.getName());
评论
String extension = com.google.common.io.Files.getFileExtension("fileName.jpg");
在这里,我做了一个小方法(但不是那么安全,并且不检查很多错误),但如果只有你在编写一个通用的 java 程序,这足以找到文件类型。这不适用于复杂的文件类型,但这些文件类型通常不会被大量使用。
public static String getFileType(String path){
String fileType = null;
fileType = path.substring(path.indexOf('.',path.lastIndexOf('/'))+1).toUpperCase();
return fileType;
}
评论
/
。lastIndexOf
john.smith.report.doc
ABC/XYZ
abc/xyz
""
null
这是一种经过测试的方法
public static String getExtension(String fileName) {
char ch;
int len;
if(fileName==null ||
(len = fileName.length())==0 ||
(ch = fileName.charAt(len-1))=='/' || ch=='\\' || //in the case of a directory
ch=='.' ) //in the case of . or ..
return "";
int dotInd = fileName.lastIndexOf('.'),
sepInd = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
if( dotInd<=sepInd )
return "";
else
return fileName.substring(dotInd+1).toLowerCase();
}
和测试用例:
@Test
public void testGetExtension() {
assertEquals("", getExtension("C"));
assertEquals("ext", getExtension("C.ext"));
assertEquals("ext", getExtension("A/B/C.ext"));
assertEquals("", getExtension("A/B/C.ext/"));
assertEquals("", getExtension("A/B/C.ext/.."));
assertEquals("bin", getExtension("A/B/C.bin"));
assertEquals("hidden", getExtension(".hidden"));
assertEquals("dsstore", getExtension("/user/home/.dsstore"));
assertEquals("", getExtension(".strange."));
assertEquals("3", getExtension("1.2.3"));
assertEquals("exe", getExtension("C:\\Program Files (x86)\\java\\bin\\javaw.exe"));
}
这个特殊的问题给我带来了很多麻烦,然后我找到了一个非常简单的解决方案来解决这个问题,我在这里发布。
file.getName().toLowerCase().endsWith(".txt");
就是这样。
评论
从文件名获取文件扩展名
/**
* The extension separator character.
*/
private static final char EXTENSION_SEPARATOR = '.';
/**
* The Unix separator character.
*/
private static final char UNIX_SEPARATOR = '/';
/**
* The Windows separator character.
*/
private static final char WINDOWS_SEPARATOR = '\\';
/**
* The system separator character.
*/
private static final char SYSTEM_SEPARATOR = File.separatorChar;
/**
* Gets the extension of a filename.
* <p>
* This method returns the textual part of the filename after the last dot.
* There must be no directory separator after the dot.
* <pre>
* foo.txt --> "txt"
* a/b/c.jpg --> "jpg"
* a/b.txt/c --> ""
* a/b/c --> ""
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to retrieve the extension of.
* @return the extension of the file or an empty string if none exists.
*/
public static String getExtension(String filename) {
if (filename == null) {
return null;
}
int index = indexOfExtension(filename);
if (index == -1) {
return "";
} else {
return filename.substring(index + 1);
}
}
/**
* Returns the index of the last extension separator character, which is a dot.
* <p>
* This method also checks that there is no directory separator after the last dot.
* To do this it uses {@link #indexOfLastSeparator(String)} which will
* handle a file in either Unix or Windows format.
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to find the last path separator in, null returns -1
* @return the index of the last separator character, or -1 if there
* is no such character
*/
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);
}
/**
* Returns the index of the last directory separator character.
* <p>
* This method will handle a file in either Unix or Windows format.
* The position of the last forward or backslash is returned.
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to find the last path separator in, null returns -1
* @return the index of the last separator character, or -1 if there
* is no such character
*/
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);
}
学分
- 从 Apache FileNameUtils 类复制 - http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/1.3.2/org/apache/commons/io/FilenameUtils.java#FilenameUtils.getExtension%28java.lang.String%29
REGEX版本怎么样:
static final Pattern PATTERN = Pattern.compile("(.*)\\.(.*)");
Matcher m = PATTERN.matcher(path);
if (m.find()) {
System.out.println("File path/name: " + m.group(1));
System.out.println("Extention: " + m.group(2));
}
或支持 null 扩展名:
static final Pattern PATTERN =
Pattern.compile("((.*\\" + File.separator + ")?(.*)(\\.(.*)))|(.*\\" + File.separator + ")?(.*)");
class Separated {
String path, name, ext;
}
Separated parsePath(String path) {
Separated res = new Separated();
Matcher m = PATTERN.matcher(path);
if (m.find()) {
if (m.group(1) != null) {
res.path = m.group(2);
res.name = m.group(3);
res.ext = m.group(5);
} else {
res.path = m.group(6);
res.name = m.group(7);
}
}
return res;
}
Separated sp = parsePath("/root/docs/readme.txt");
System.out.println("path: " + sp.path);
System.out.println("name: " + sp.name);
System.out.println("Extention: " + sp.ext);
*nix 的结果:路径:/root/docs/
名称:自述扩展
名:
txt
对于 windows,parsePath(“c:\windows\readme.txt”):
path: c:\windows\
name: readme
扩展名: txt
这是以 Optional 作为返回值的版本(因为您无法确定文件具有扩展名)...还有健全性检查......
import java.io.File;
import java.util.Optional;
public class GetFileExtensionTool {
public static Optional<String> getFileExtension(File file) {
if (file == null) {
throw new NullPointerException("file argument was null");
}
if (!file.isFile()) {
throw new IllegalArgumentException("getFileExtension(File file)"
+ " called on File object that wasn't an actual file"
+ " (perhaps a directory or device?). file had path: "
+ file.getAbsolutePath());
}
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
if (i > 0) {
return Optional.of(fileName.substring(i + 1));
} else {
return Optional.empty();
}
}
}
在不使用任何库的情况下,可以使用 String 方法拆分,如下所示:
String[] splits = fileNames.get(i).split("\\.");
String extension = "";
if(splits.length >= 2)
{
extension = splits[splits.length-1];
}
String path = "/Users/test/test.txt";
String extension = "";
if (path.contains("."))
extension = path.substring(path.lastIndexOf("."));
返回“.txt”
如果您只想要“txt”,请使path.lastIndexOf(".") + 1
评论
试试这个。
String[] extension = "adadad.adad.adnandad.jpg".split("\\.(?=[^\\.]+$)"); // ['adadad.adad.adnandad','jpg']
extension[1] // jpg
从所有其他答案中可以明显看出,没有足够的“内置”功能。这是一种安全而简单的方法。
String getFileExtension(File file) {
if (file == null) {
return "";
}
String name = file.getName();
int i = name.lastIndexOf('.');
String ext = i > 0 ? name.substring(i + 1) : "";
return ext;
}
我喜欢 spectre 回答的简单性,在他的一条评论中链接的是指向另一个答案的链接,该答案修复了 EboMike 提出的另一个问题中的点。
在不实现某种第三方 API 的情况下,我建议:
private String getFileExtension(File file) {
String name = file.getName().substring(Math.max(file.getName().lastIndexOf('/'),
file.getName().lastIndexOf('\\')) < 0 ? 0 : Math.max(file.getName().lastIndexOf('/'),
file.getName().lastIndexOf('\\')));
int lastIndexOf = name.lastIndexOf(".");
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf + 1); // doesn't return "." with extension
}
例如,在必须传入文件格式的任何 ImageIO 写入
方法中,这样的东西可能很有用。
当您可以 DIY 时,为什么要使用整个第三方 API?
这是 Java 8 的另一个单行代码。
String ext = Arrays.stream(fileName.split("\\.")).reduce((a,b) -> b).orElse(null)
其工作原理如下:
- 使用 “.” 将字符串拆分为字符串数组。
- 将数组转换为流
- 使用 reduce 获取流的最后一个元素,即文件扩展名
如果你在项目中使用 Spring 框架,那么你可以使用 StringUtils
import org.springframework.util.StringUtils;
StringUtils.getFilenameExtension("YourFileName")
private String getExtension(File file)
{
String fileName = file.getName();
String[] ext = fileName.split("\\.");
return ext[ext.length -1];
}
流利的方式:
public static String fileExtension(String fileName) { return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0) .filter(i-> i > fileName.lastIndexOf(File.separator)) .map(fileName::substring).orElse(""); }
Java 20 EA
从 Java 20 EA(抢先体验)开始,终于有了一个新的方法 Path#getExtension
,它将扩展返回为:String
Paths.get("/Users/admin/notes.txt").getExtension(); // "txt"
Paths.get("/Users/admin/.gitconfig").getExtension(); // "gitconfig"
Paths.get("/Users/admin/configuration.xml.zip").getExtension(); // "zip"
Paths.get("/Users/admin/file").getExtension(); // null
评论
"txt"
"filename.txt"
"filename,txt"
path.substring(path.lastIndexOf("."));
".txt"
"filename.txt"
StringIndexOutOfBoundsException
Path#getExtension