Java: Example - Display Extension
This program reads in a file name and displays the extension (that last part of the name after the final dot).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// Purpose: Display the extension (with .) of a file name.
// File : extension/FileExt.java
// Author : Fred Swartz
// Date : 2005-09-06
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);
}
}
|