java中file获取后缀方法
时间: 2024-01-16 18:02:29 浏览: 65
在Java中,可以使用File类的getName()方法和lastIndexOf()方法来获取文件的后缀名。示例代码如下:
```java
import java.io.File;
public class GetFileExtension {
public static void main(String[] args) {
File file = new File("example.txt");
String fileName = file.getName();
String fileExtension = "";
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
fileExtension = fileName.substring(dotIndex + 1);
}
System.out.println(fileExtension); // 输出:txt
}
}
```
其中,lastIndexOf()方法会获取文件名中最后一个"."(点)的位置,如果存在,则将点后面的字符串作为文件的后缀名。如果文件名中没有点或者点在文件名的第一个位置,那么文件没有后缀名。
相关问题
java 获取file后缀,Java获取文件后缀的方法
获取Java文件的后缀有多种方法,这里提供两种常见的方法:
1. 使用String类中的substring()方法和lastIndexOf()方法来获取文件后缀名。
```java
String fileName = "example.txt";
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
```
2. 使用Java 7中引入的Files类的probeContentType()方法来获取文件的MIME类型,然后从中提取文件扩展名。
```java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class FileExtensionExample {
public static void main(String[] args) throws IOException {
File file = new File("example.txt");
String mimeType = Files.probeContentType(file.toPath());
String fileExtension = mimeType.split("/")[1];
}
}
```
以上两种方法都可以用来获取Java文件的后缀名。
java中获取MultipartFile的文件后缀
可以使用MultipartFile的`getOriginalFilename()`方法获取文件名,然后再从文件名中提取文件后缀。示例代码如下:
```java
MultipartFile file = ...;
String fileName = file.getOriginalFilename();
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
```
上述代码中,`fileName.lastIndexOf(".")`获取文件名中最后一个点号的位置,再加1就是文件后缀的起始位置,然后使用`substring()`方法从文件名中截取后缀部分。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)