java 判断文件类型

Python015

java 判断文件类型,第1张

如果只是简单的复制、截取等操作,直接使用字节流对文件进行I/O操作就可以了;

一般判断一个文件是否是二进制文件,只是判断一下文件的内容中是否含有0x00-0x07这八个字符内容,如果有的话,就是二进制文件。

java web识别文件的类型是通过文件后缀识别的。

1、写一个识别文件类型方法

public String identifyFileTypeUsingFilesProbeContentType(final String fileName) {

String fileType = "Undetermined"

final File file = new File(fileName)

try {

  fileType = Files.probeContentType(file.toPath())

} catch (IOException ioException) {

 out.println( "ERROR: Unable to determine file type for " + fileName + " due to exception " + ioException)

}

return fileType

}

2、最常见的文件类型:

主要以下几种方法:

这个MimetypesFileMap类会映射出一个file的Mime Type,这些Mime Type类型是在activation.jar包里面的资源文件中定义的

import javax.activation.MimetypesFileTypeMap

import java.io.File

class GetMimeType {

public static void main(String args[]) {

File f = new File("test.gif")

System.out.println("Mime Type of " + f.getName() + " is " +

new MimetypesFileTypeMap().getContentType(f))

// expected output :

// "Mime Type of test.gif is image/gif"

}

}

使用 java.net.URL

警告:这个方法非常慢

与上面所说的匹配后缀名类似。后缀名和mime-type的映射关系被定义在[jre_home]\lib\content-types.properties这个文件中

import java.net.*

public class FileUtils{

public static String getMimeType(String fileUrl)

throws java.io.IOException, MalformedURLException

{

String type = null

URL u = new URL(fileUrl)

URLConnection uc = null

uc = u.openConnection()

type = uc.getContentType()

return type

}

public static void main(String args[]) throws Exception {

System.out.println(FileUtils.getMimeType("file://c:/temp/test.TXT"))

// output : text/plain

}

}

还有一种方式:就是取文件名最后一个“.”后的内容,通过人来判断如

String fileName = "aaa.txt"

String fileType =“txt”//通过方法取出方法类型为

String type = ""

if( fileTyep.equals("txt")){

type = "记事本"

}else if(fileTyep.equals("img")){

type = "img图片"

}