Getting A File's Mime Type In Java

后端 未结 23 2722
南方客
南方客 2020-11-21 06:53

I was just wondering how most people fetch a mime type from a file in Java? So far I\'ve tried two utils: JMimeMagic & Mime-Util.

Th

23条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 07:12

    I did it with following code.

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class MimeFileType {
    
        public static void main(String args[]){
    
            try{
                URL url = new URL ("https://www.url.com.pdf");
    
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setDoOutput(true);
                InputStream content = (InputStream)connection.getInputStream();
                connection.getHeaderField("Content-Type");
    
                System.out.println("Content-Type "+ connection.getHeaderField("Content-Type"));
    
                BufferedReader in = new BufferedReader (new InputStreamReader(content));
    
            }catch (Exception e){
    
            }
        }
    }
    

提交回复
热议问题