2

How do I print the type of a file in java?

I am able to print the length, whether it is readable or writable, but can you suggest a way to print the type of file?

Is there any built in method to find the type of file?

Rob Baillie
  • 3,436
  • 2
  • 20
  • 34

3 Answers3

2

If you need mime type of the file you can use Files.probeContentType(path) if you use Java 7.

Or If you need File Extension

Method 1:

You can use this to get the extension.

File file = new File("C:"/java.txt");
String fileName = file.getName();
if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
System.out.println(fileName.substring(fileName.lastIndexOf(".")+1));

Method 2:

You can use FilenameUtils.getExtension(String filename) from Apache Commons IO

ashokramcse
  • 2,841
  • 2
  • 19
  • 41
0

Try following:

File file=new File("E:/one.txt");
System.out.println(file.getName().substring(file.getName().lastIndexOf('.'), file.getName().length()));

output :

.txt
Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
-1
    File file = new File("D:\\Storage\\example.js");
    String[] splitStrings = file.getName().split("\\.");
    String extension = splitStrings[splitStrings.length-1];
    System.out.println(extension); //prints js
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428