首页 技术 正文
技术 2022年11月15日
0 收藏 619 点赞 4,172 浏览 1365 个字

在Java 7中增加了新的一个方法——probeContentType,其主要作用是可以判断文件的content type。相应代码如下所示:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileContentType {
public static void main(String[] args) { printContentType("D:/Downloads/java.txt");
printContentType("D:/Downloads/java.ppt");
printContentType("D:/Downloads/java.doc");
printContentType("D:/Downloads/java.avi");
}
private static void printContentType(String pathToFile) { Path path = Paths.get(pathToFile);
String contentType = null;
try {
contentType = Files.probeContentType(path);
} catch (IOException e) { e.printStackTrace();
}
System.out.println("File content type is : " + contentType);
}
}

在C#中没有对应的方法,不过要实现同样的功能并不困难。

using System;
using System.IO;
using Microsoft.Win32;namespace Demo
{
class Program
{
static void Main(string[] args)
{
PrintContentType("D:/Downloads/java.txt");
PrintContentType("D:/Downloads/java.ppt");
PrintContentType("D:/Downloads/java.doc");
PrintContentType("D:/Downloads/java.jar"); Console.ReadKey();
} private static void PrintContentType(string pathToFile)
{
string result = string.Empty;
string ext = Path.GetExtension(pathToFile);
using (RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(ext))
{
if (registryKey != null)
{
var value = registryKey.GetValue("Content Type");
result = value == null ? "null" : value.ToString();
}
}
Console.WriteLine(result);
}
}
}

因为相关的content type信息其实都可以从注册表中取得,故而只需要对注册表做一点操作,即可以达到同样的功能。

原文同步发布于我的个人博客

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,954
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774