代码:
public class filename {/*** Get File extension in java* @param args*/public static void main(String[] args) {File file = new File("/Users/pankaj/book.txt");System.out.println("File extension is: "+getFileExtension(file));file = new File("/Users/pankaj/header.png");System.out.println("File extension is: "+getFileExtension(file));file = new File("/Users/pankaj/java.util.txt");System.out.println("File extension is: "+getFileExtension(file));file = new File("/Users/pankaj/snow");System.out.println("File extension is: "+getFileExtension(file));}private static String getFileExtension(File file) {String fileName = file.getName();if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)return fileName.substring(fileName.lastIndexOf(".")+1);else return " ";
运行结果: