Tuesday 31 May 2011

Detecting Extension Filename in JAVA

import javax.swing.*;

public class FileExt {

    public static void main(String[] args) {
        //... Declare local variables.
        String fileName;   // The file name the user entered.
        String extension;  // The extension.

        //... Input a file name and remove whitespace.
        fileName = JOptionPane.showInputDialog(null, "Enter file name.");
        fileName = fileName.trim();

        //... Find the position of the last dot.  Get extension.
        int dotPos = fileName.lastIndexOf(".");
        extension = fileName.substring(dotPos);

        //... Output extension.
        JOptionPane.showMessageDialog(null, "Extension is " + extension);
    }
}

No comments: