1

I have this program here that scans for all the files in WinRar folder and determines whether it is a directory or file. However I want to also make it able to determine the extension on the file. For example lets say I have setup.exe in WinRar and the program prints Setup.exe has the extension .exe

public class SystemCommands{

public static void main (String args[]){



String dir_name = "C:\\Program Files\\WinRAR\\"; 
File dir = new File(dir_name);



File[] dir_list = dir.listFiles();
for(int i=0;i<dir_list.length;++i)
{
    System.out.println(dir_list[i].getName());
    System.out.println("Is it a directory = " + dir_list[i].isDirectory());
    System.out.println("Is it a file = " + dir_list[i].isFile());

}

}



}

3 Answers 3

1

I like to use Commons IO, it has FilenameUtils#getExtension:

String extension = FilenameUtils.getExtension(dir_list[i].getName());
0

Either you can use a one simple line as answered by Thilo but use a 3rd party API for that.
OR
You can find the "." in the absolute file path and then read the Sequence of chars after the "."
example:

String path = dir_list[i].getAbsolutePath();
int position  = path.indexOf(".");
String extension = path.subString(position);

you should go with Thilo's Answer though :D

2
  • You probably want lastIndexOf. And handle the case where there is no dot.
    – Thilo
    Mar 19, 2014 at 23:28
  • Feel free to edit my answer with a seperate "lastIndexOF" example below mine.. for future visitors.
    – Sharp Edge
    Mar 19, 2014 at 23:31
0

Simply parse the path to check the last index of dot (.) and do substring to get extension.

private static String getExtension(File file)
    {
        return getExtension(file.getAbsolutePath());
    }

    private static String getExtension(String path)
    {
        String extension = null;

        int lastIndexOfDot = path.lastIndexOf(".");

        if (lastIndexOfDot != -1)
        {
            extension = path.substring(lastIndexOfDot + 1);
        }
        return extension;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.