
String extName = name.substring(name.lastIndexOf(".") + 1)//扩展名
System.out.println(extName)
java源文件的扩展名为”.java“。
解释:这个是固定规范,源文件顾名思义就是最原始的没有经过编译的文件,这个在java中就是”.java”
备注:编译后的文件扩展名是“.class”文件。
主要以下几种方法:
这个MimetypesFileMap类会映射出一个file的Mime Type,这些Mime Type类型是在activation.jar包里面的资源文件中定义的
import javax.activation.MimetypesFileTypeMapimport 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图片"
}。。。。。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)