迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Java >

如何在 Java 中获取文件的文件扩展名

作者:迹忆客 最近更新:2023/08/14 浏览次数:

本文介绍了如何在 Java 中获取文件的文件扩展名,还列举了一些示例代码来理解这个话题。


使用 Java 中的 getExtension() 方法获取文件扩展名

要获得文件的扩展名,我们可以使用 FilenameUtils 类的 getExtension() 方法。这个方法返回文件的扩展名。由于这个方法属于 Apache commons 库,所以你必须从 Apache 官网下载这个库才能在项目中使用 JAR。

import org.apache.commons.io.FilenameUtils;

public class SimpleTesting {
	public static void main(String[] args){
		String fileName = "student-records.pdf";
		String fe = FilenameUtils.getExtension(fileName);
		System.out.println("File extension is : "+fe);
	}
}

输出:

File extension is : pdf

用 Java 中的 lastIndexOf() 方法获取文件的扩展名

如果你不想使用任何内置的方法,那么使用给定的代码示例,使用 lastIndexOf() 方法来获取文件扩展名。这是最简单易行的方法,只涉及字符串方法。请看下面的例子。

public class SimpleTesting {
	public static void main(String[] args){
		String fileName = "student-records.pdf";
		String fe = "";
		int i = fileName.lastIndexOf('.');
		if (i > 0) {
		    fe = fileName.substring(i+1);
		}
		System.out.println("File extension is : "+fe);
	}
}

输出:

File extension is : pdf

用 Java 中的字符串解析获取文件的文件扩展名

这是另一种解决方案,包括几种情况,其中包括(如果文件路径中有点 .)。即使文件路径之间有点(.),这种方法也会返回准确的结果。请看下面的例子。

public class SimpleTesting {
	public static void main(String[] args){
		String fileName = "folder\s.gr\fg\student-records.pdf";
		String fe = "";
		char ch;
		int len;
		if(fileName==null || (len = fileName.length())==0 || (ch = fileName.charAt(len-1))=='/' || ch=='\\' ||ch=='.' ) {
			fe = "";
		}
		int dotInd = fileName.lastIndexOf('.'),	sepInd = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
		if( dotInd <= sepInd ) {
			fe = "";
		}
		else {
			fe = fileName.substring(dotInd+1).toLowerCase();
		}
		System.out.println("File extension is : "+fe);
	}
}

输出:

File extension is : pdf

使用 Java 中的 replaceAll() 方法获取文件的文件扩展名

我们可以使用 replaceAll() 方法来获取文件扩展名,就像我们在下面的例子中所做的那样。我们在这个方法中使用正则表达式并将结果收集到一个变量中。

public class SimpleTesting {
	public static void main(String[] args){
		String fileName = "folder\s.gr\fg\student-records.pdf";
		String fe = "";
		fe = fileName.replaceAll("^.*\\.(.*)$", "$1");
		System.out.println("File extension is : "+fe);
	}
}

输出:

File extension is : pdf

在 Java 中使用 contains()lastIndexOf() 方法获取文件扩展名

contains() 方法用于检查指定的字符是否存在于字符串中,lastIndexOf() 方法返回指定字符的索引值,该索引值被传递到 substring() 方法中以获取文件扩展名。我们在这段代码中使用这些方法来获取文件扩展名。请看下面的例子。

public class SimpleTesting {
	public static void main(String[] args){
		String fileName = "folder\s.gr\fg\student-records.pdf";
		String fe = "";
		if (fileName.contains("."))
		     fe = fileName.substring(fileName.lastIndexOf(".")+1);
		System.out.println("File extension is : "+fe);
	}
}

输出:

File extension is : pdf

使用 Java 中的三元运算符获取文件扩展名

如果你对三元运算符(?, :)很熟悉,那么就把它和 substring()lastIndexOf() 方法一起使用。它减少了代码的行数,并在一条语句中返回结果。

public class SimpleTesting {
	public static void main(String[] args){
		String fileName = "folder\s.gr\fg\student-records.pdf";
		String fe = "";
		if (fileName.contains(".")) {
			int i = fileName.lastIndexOf('.');
			fe = i > 0 ? fileName.substring(i + 1) : "";
		}
		System.out.println("File extension is : "+fe);
	}
}

输出:

File extension is : pdf

在 Java 中使用 stream() 方法获取文件的文件扩展名

我们可以使用 Arrays 类的 stream() 方法将文件名转换成流,并使用 split() 方法将文件名从点(.)中断开。请看下面的例子。

import java.util.Arrays;
public class SimpleTesting {
	public static void main(String[] args){
		String fileName = "folder\s.gr\fg\student-records.pdf";
		String fe = "";
		if (fileName.contains(".")) {
			fe = Arrays.stream(fileName.split("\\.")).reduce((a,b) -> b).orElse(null);
		}
		System.out.println("File extension is : "+fe);
	}
}

输出:

File extension is : pdf

使用 Java 中的 Regex 获取文件的文件扩展名

这是另一个使用 regex 包的解决方案。在这个 Java 例子中,Pattern 类的 compile()matcher() 方法被用来获取文件的扩展名。请看下面的例子。

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SimpleTesting {
	public static void main(String[] args){
		String fileName = "folder\s.gr\fg\student-records.pdf";
		String fe = "";
		final Pattern PATTERN = Pattern.compile("(.*)\\.(.*)");
		Matcher m = PATTERN.matcher(fileName);
		if (m.find()) {
			fe = m.group(2);
		}
		System.out.println("File extension is : "+fe);
	}
}

输出:

File extension is : pdf

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

如何从 Pandas 的日期时间列中提取月份和年份

发布时间:2024/04/23 浏览次数:160 分类:Python

我们可以分别使用 dt.year()和 dt.month()方法从 Datetime 列中提取出年和蛾。我们还可以使用 pandas.DatetimeIndex.month 以及 pandas.DatetimeIndex.year 和 strftime()方法提取年份和月份。

如何获取 Pandas DataFrame 的行数

发布时间:2024/04/23 浏览次数:71 分类:Python

本教程介绍如何通过使用 shape,len()来获取 Pandas DataFrame 的行数,以及有多少行元素满足条件。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便