Places an extension on a filename if it does not already exist. - Java java.io

Java examples for java.io:File Extension Name

Description

Places an extension on a filename if it does not already exist.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String filename = "java2s.com";
        String ext = "java2s.com";
        System.out.println(addExtIfNecessary(filename, ext));
    }/*from   ww w  . j  ava 2 s.co  m*/

    /**
     * Places an extension on a filename if it does not already exist.
     * @param filename Path to the file.
     * @param ext Extension of the file.
     */
    public static String addExtIfNecessary(String filename, String ext) {
        if (hasExtension(filename, ext))
            return (filename);
        return (setExtension(filename, ext));
    }

    public static boolean hasExtension(String filename, String ext) {
        int index = filename.lastIndexOf(".");
        if (index == -1)
            return (false);
        return (filename.substring(index + 1).compareTo(ext) == 0);
    }

    public static String setExtension(String filename, String ext) {
        if (hasExtension(filename, ext))
            return (filename);
        int index = filename.lastIndexOf(".");
        if (index == -1)
            return (filename + "." + ext);
        return (filename.substring(0, index + 1) + ext);

    }
}

Related Tutorials