theTuxRacer
theTuxRacer

Reputation: 13869

Is there any native way of detecting the file extension?

At the moment, I am doing the following, which is not what I am looking for. I just want to be able to detect the file extension, and depending on that, either copy it to the server, or reject it.

    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    FileInputStream is1 = new FileInputStream(file);
    String mimeType = mimeTypesMap.getContentType(file);

    InputStream is2 = new BufferedInputStream(new FileInputStream(file));
    String content = URLConnection.guessContentTypeFromStream(is2);

    System.out.println(mimeType);
    System.out.println(content);

I get the mimetype, but again, thats not what I want. URL.guessContentFromStream() always returns null.

Does play have a native way to read the file extension? What other solutions are there?

Thanks.

Upvotes: 0

Views: 1653

Answers (2)

Rosdi Kasim
Rosdi Kasim

Reputation: 25956

Detecting file extension is pretty trivial, here is what I normally do:

String filename = "a long.filename.ext";
String extension = filename.substring(filename.lastIndexOf('.') + 1);

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Use FileTypeDetector from package java.nio.file.spi

See this link for more details:

http://openjdk.java.net/projects/nio/javadoc/java/nio/file/spi/FileTypeDetector.html

/////Edited//////

Try FileNameExtensionFilter

See this link:

http://docs.oracle.com/javase/6/docs/api/javax/swing/filechooser/FileNameExtensionFilter.html

Upvotes: 2

Related Questions