明确一点,我并不是在寻找MIME类型。
假设我有以下输入:/path/to/file/foo.txt
我想要一种方法来分解这个输入,特别是扩展为.txt。在Java中有任何内置的方法来做到这一点吗?我希望避免编写自己的解析器。
明确一点,我并不是在寻找MIME类型。
假设我有以下输入:/path/to/file/foo.txt
我想要一种方法来分解这个输入,特别是扩展为.txt。在Java中有任何内置的方法来做到这一点吗?我希望避免编写自己的解析器。
当前回答
在本例中,使用FilenameUtils。getExtension来自Apache Commons IO
下面是一个如何使用它的例子(你可以指定完整路径或只是文件名):
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
其他回答
String extension = com.google.common.io.Files.getFileExtension("fileName.jpg");
我发现了一个更好的方法来找到扩展混合以上所有的答案
public static String getFileExtension(String fileLink) {
String extension;
Uri uri = Uri.parse(fileLink);
String scheme = uri.getScheme();
if (scheme != null && scheme.equals(ContentResolver.SCHEME_CONTENT)) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
extension = mime.getExtensionFromMimeType(CoreApp.getInstance().getContentResolver().getType(uri));
} else {
extension = MimeTypeMap.getFileExtensionFromUrl(fileLink);
}
return extension;
}
public static String getMimeType(String fileLink) {
String type = CoreApp.getInstance().getContentResolver().getType(Uri.parse(fileLink));
if (!TextUtils.isEmpty(type)) return type;
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getMimeTypeFromExtension(FileChooserUtil.getFileExtension(fileLink));
}
private String getExtension(File file)
{
String fileName = file.getName();
String[] ext = fileName.split("\\.");
return ext[ext.length -1];
}
如果在Android上,你可以使用这个:
String ext = android.webkit.MimeTypeMap.getFileExtensionFromUrl(file.getName());
// Modified from EboMike's answer
String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));
扩展应该有“.txt”在它运行时。