java获取文件名后缀

代码:

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 " ";
     

运行结果:
java获取文件名后缀_第1张图片

你可能感兴趣的:(java,开发语言,后端)