在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信息其實都可以從注冊表中取得,故而只需要對注冊表做一點操作,即可以達到同樣的功能。
原文同步發布於我的個人博客