Java I/O How to - Get file Content Type via java.nio.file.Files








Question

We would like to know how to get file Content Type via java.nio.file.Files.

Answer

/*from w w w.  j a  v  a 2 s.  c  o m*/
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) throws Exception {
    displayContentType("/home/docs/users.txt");
    displayContentType("/home/docs/Chapter 2.doc");
    displayContentType("/home/docs/java.exe");
  }

  static void displayContentType(String pathText) throws Exception {
    Path path = Paths.get(pathText);
    String type = Files.probeContentType(path);
    System.out.println(type);
  }

}

The code above generates the following result.