Reputation: 25
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?
Upvotes: 2
Views: 1626
Reputation: 2861
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
Upvotes: 2
Reputation: 5868
Try following:
File file=new File("E:/one.txt");
System.out.println(file.getName().substring(file.getName().lastIndexOf('.'), file.getName().length()));
output :
.txt
Upvotes: 0
Reputation: 81588
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
Upvotes: -1