如何在Java中获取文件的文件扩展名?
我要说的是,我不是在寻找MIME类型 假设我有以下输入:如何在Java中获取文件的文件扩展名?,java,file,io,Java,File,Io,我要说的是,我不是在寻找MIME类型 假设我有以下输入:/path/to/file/foo.txt 我想要一种方法来分解这个输入,特别是将其分解为扩展名的.txt。在Java中有没有内置的方法来实现这一点?我希望避免编写自己的解析器。您真的需要一个“解析器”吗 String extension = ""; int i = fileName.lastIndexOf('.'); if (i > 0) { extension = fileName.substring(i+1); }
/path/to/file/foo.txt
我想要一种方法来分解这个输入,特别是将其分解为扩展名的.txt
。在Java中有没有内置的方法来实现这一点?我希望避免编写自己的解析器。您真的需要一个“解析器”吗
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i+1);
}
假设您处理的是像文件名这样的简单窗口,而不是像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);
}
运行时,扩展名中应该包含“.txt”。JFileChooser怎么样?这并不简单,因为您需要解析它的最终输出
JFileChooser filechooser = new JFileChooser();
File file = new File("your.txt");
System.out.println("the extension type:"+filechooser.getTypeDescription(file));
这是一种MIME类型
好吧……我忘了你不想知道它的MIME类型
以下链接中的有趣代码:
/*
*获取文件的扩展名。
*/
公共静态字符串getExtension(文件f){
字符串ext=null;
字符串s=f.getName();
int i=s.lastIndexOf('.');
如果(i>0&&i
相关问题:
如何(使用Java 1.5正则表达式):
如果您使用库,则可以求助于实用程序类。它有一个具体的方法。例如:
String path = "c:/path/to/file/foo.txt";
String ext = Files.getFileExtension(path);
System.out.println(ext); //prints txt
此外,您还可以使用类似的函数获取文件名:
这里有一个方法可以正确处理
.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
,因为如果字符串中有一些斜杠,它不必搜索整个字符串
原始字符串中的char[]
被重用,不会在那里添加垃圾。在这种情况下,请使用from
以下是如何使用它的示例(您可以指定完整路径或仅指定文件名):
Maven依赖项:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
格雷德尔·科特林DSL
implementation("commons-io:commons-io:2.6")
其他的只是一个基于正则表达式的替代方案。没那么快,也没那么好
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);
}
Java有一种内置的方法来处理这一问题,它可以满足您的需要:
File f = new File("/path/to/file/foo.txt");
String ext = Files.probeContentType(f.toPath());
if(ext.equalsIgnoreCase("txt")) do whatever;
请注意,此静态方法使用规范检索“内容类型”,内容类型可能会有所不同。My dirty(我的脏)并且可能最小,请使用:
private String getFileExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf(".");
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf);
}
请注意,第一个*
是贪婪的,因此它将尽可能地抓取最可能的字符,然后只剩下最后一个点和文件扩展名。如果您计划使用Apache commons io,并且只想检查文件扩展名,然后执行一些操作,则可以使用以下代码段:
if(FilenameUtils.isExtension(file.getName(),"java")) {
someoperation();
}
如果在Android上,您可以使用:
String ext = android.webkit.MimeTypeMap.getFileExtensionFromUrl(file.getName());
在这里,我提出了一个小方法(但是没有那么安全,也没有检查许多错误),但是如果只有您在编写一个通用java程序,那么这就足够找到文件类型了。这不适用于复杂的文件类型,但通常不会使用太多的文件类型
public static String getFileType(String path){
String fileType = null;
fileType = path.substring(path.indexOf('.',path.lastIndexOf('/'))+1).toUpperCase();
return fileType;
}
这是一种经过测试的方法
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();
}
这个问题给了我很多麻烦,然后我找到了一个非常简单的解决方案,我在这里发布
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);
}
/**
*扩展分隔符字符。
*/
私有静态最终字符扩展_分隔符='';
/**
*Unix分隔符。
*/
私有静态最终字符UNIX_分隔符='/';
/**
*Windows分隔符字符。
*/
私有静态最终字符窗口\ u分隔符=“\\”;
/**
*系统分隔符字符。
*/
私有静态最终字符系统_SEPARATOR=File.separatorChar;
/**
*获取文件名的扩展名。
*
*此方法返回文件名最后一个点后的文本部分。
*点后面不能有目录分隔符。
*
*foo.txt-->“txt”
*a/b/c.jpg-->“jpg”
*a/b.txt/c-->“
*a/b/c-->“
*
*
*无论代码在哪台机器上运行,输出都是相同的。
*
*@param filename用于检索扩展名的文件名。
*@返回文件的扩展名,如果不存在,则返回空字符串。
*/
公共静态字符串getExtension(字符串文件名){
如果(文件名==null){
返回null;
}
int index=indexOfExtension(文件名);
如果(索引==-1){
返回“”;
}否则{
返回filename.substring(索引+1);
}
}
/**
*返回最后一个扩展分隔符字符(点)的索引。
*
*此方法还检查最后一个点后是否没有目录分隔符。
*为此,它使用{@link#indexoflastsseparator(String)},它将
*处理Unix或Windows格式的文件。
*
*无论代码在哪台机器上运行,输出都是相同的。
*
*@param filename在中查找最后一个路径分隔符的文件名,null返回-1
*@返回最后一个分隔符的索引,如果有,则返回-1
*没有这样的性格
*/
公共静态int-indexOfExtension(字符串文件名){
如果(文件名==null){
返回-1;
}
int extensionPos=filename.lastIndexOf(扩展名分隔符);
int lastSeparator=indexOfLastSeparator(文件名);
返回(lastSeparator>extensionPos?-1:extensionPos);
}
/**
*返回最后一个目录分隔符字符的索引。
*
*此方法将处理Unix或Windows格式的文件。
*返回最后一个向前或向后斜杠的位置。
*
*无论代码在哪台机器上运行,输出都是相同的。
*
*@param filename在中查找最后一个路径分隔符的文件名,null返回-1
*@返回最后一个分隔符的索引,如果有,则返回-1
*不是苏
private String getFileExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf(".");
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf);
}
.replaceAll("^.*\\.(.*)$", "$1")
if(FilenameUtils.isExtension(file.getName(),"java")) {
someoperation();
}
String ext = android.webkit.MimeTypeMap.getFileExtensionFromUrl(file.getName());
String extension = com.google.common.io.Files.getFileExtension("fileName.jpg");
public static String getFileType(String path){
String fileType = null;
fileType = path.substring(path.indexOf('.',path.lastIndexOf('/'))+1).toUpperCase();
return fileType;
}
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);
}
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));
}
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);
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[] 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("."));
String[] extension = "adadad.adad.adnandad.jpg".split("\\.(?=[^\\.]+$)"); // ['adadad.adad.adnandad','jpg']
extension[1] // jpg
@Test
public void getFileExtension(String fileName){
String extension = null;
List<String> list = new ArrayList<>();
do{
extension = FilenameUtils.getExtension(fileName);
if(extension==null){
break;
}
if(!extension.isEmpty()){
list.add("."+extension);
}
fileName = FilenameUtils.getBaseName(fileName);
}while (!extension.isEmpty());
Collections.reverse(list);
System.out.println(list.toString());
}
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));
}
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;
}
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
}
String ext = Arrays.stream(fileName.split("\\.")).reduce((a,b) -> b).orElse(null)
import org.springframework.util.StringUtils;
StringUtils.getFilenameExtension("YourFileName")