java判断文件类型
时间: 2023-02-09 10:36:22 浏览: 80
Java可以使用文件后缀名或文件头来判断文件类型。
使用文件后缀名判断:
- 首先使用File类获取文件名,例如:File file = new File("example.txt");
- 然后使用getName()方法获取文件名,例如:String fileName = file.getName();
- 接着使用substring()方法截取文件后缀名,例如:String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
使用文件头判断:
- 首先使用FileInputStream类读取文件头,例如:FileInputStream inputStream = new FileInputStream(file);
- 然后使用read()方法读取文件头前几个字节,例如:byte[] fileHead = new byte[10]; inputStream.read(fileHead);
- 接着使用java的数组比较功能来匹配文件头,判断文件类型
注意: 上述第二种方法可能会有误差,因为有些文件并没有固定的头。
相关问题
java 判断文件类型
你可以使用 Java 的 Files 类和 ProbeContentType 方法来判断文件类型。具体代码如下:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileTypeChecker {
public static void main(String[] args) throws IOException {
Path file = Paths.get("path/to/your/file");
String fileType = Files.probeContentType(file);
if (fileType != null) {
System.out.println("File type: " + fileType);
} else {
System.out.println("Unable to determine file type.");
}
}
}
```
其中,`path/to/your/file` 是你要判断文件类型的文件路径。该代码会输出文件类型,如果无法判断文件类型则会输出 `Unable to determine file type.`。
simplemagic java 判断文件类型
可以使用Java API中的Files.probeContentType(Path path)方法来判断文件类型。该方法会返回文件的MIME类型。
示例代码:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public static void main(String[] args) throws IOException {
Path path = Paths.get("path/to/file");
String fileType = Files.probeContentType(path);
System.out.println(fileType);
}
}
```
注意:该方法的判断依据是文件扩展名,因此可能会存在一定的误判风险。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)