往服务器上上传图片的时候,需要获取图片的类型,我们可能会想到通过文件后缀名来进行获取,但是万一这个文件是别的类型的数据,但是通过修改后缀名来改成图片文件,就会造成脏数据。比如我们将一个.zip文件通过修改后缀,修改成.jpg,仍然可以进行上传。
import java.io.*;
import java.net.URLConnection;
public class Test3 {
private static String getFileType(String pic_path){
String file_type = "";
try{
InputStream file_stream = new BufferedInputStream(new FileInputStream(pic_path));
file_type = URLConnection.guessContentTypeFromStream(file_stream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return file_type;
}
public static void main(String[] args) {
String pic_path="d:/test123.jpg";
String filetype=getFileType(pic_path);
System.out.println(filetype);
}
}
输出结果如下: