tags:

views:

87

answers:

3

Just to be clear, I'm not looking for the MIME type.

Let's say i have the input: "/path/to/file/foo.txt"

I'd like a way to break this input up, specifically into ".txt" for the extension. Is there any built in ways to do this in Java? I'm still new and would like to avoid writing my own parser... :)

Thanks!

+5  A: 

Do you really need a "parser" for this?

String extension = "";

int i = fileName.lastIndexOf('.');
if (i > 0) {
    extension = fileName.substring(i+1);
}

Assuming that you're dealing with simple Windows-like file names, not something like "archive.tar.gz".

Btw, for the case that a directory may have a '.', but the filename itself doesn't (like /path/to.a/file), you can do

String extension = "";

int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\');

if (i > p) {
    extension = fileName.substring(i+1);
}
EboMike
Thanks! Sure you might need a parser/object for this, if you wanted to do more manipulations than just the extension... say if you want just the path, the parent directory, the file name (minus the extension), etc. I'm coming from C# and .Net where we have this: http://msdn.microsoft.com/en-us/library/system.io.fileinfo_members.aspx
longda
As you say, there are a number of things to think about, beyond just using the naive lastIndexOf("."). I would guess that Apache Commons has a method for this, which takes all of the little tricky potential problems into account.
MatrixFrog
A: 
// Modified from EboMike's answer

String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));

extension should have ".txt" in it when run.

longda
Will crash if the name doesn't have an extension.
EboMike
Ah, good catch!
longda
A: 

How about JFileChooser? It is not straightforward as you will need to parse its final output...

JFileChooser filechooser = new JFileChooser();
File file = new File("your.txt");
System.out.println("the extension type:"+filechooser.getTypeDescription(file));

which is a MIME type...

OK...I forget that you don't want to know its MIME type.

Interesting code in the following link: http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html

/*
 * Get the extension of a file.
 */  
public static String getExtension(File f) {
    String ext = null;
    String s = f.getName();
    int i = s.lastIndexOf('.');

    if (i > 0 &&  i < s.length() - 1) {
        ext = s.substring(i+1).toLowerCase();
    }
    return ext;
}

Related question: http://stackoverflow.com/questions/941272/how-do-i-trim-a-file-extension-from-a-string-in-java

eee