Gaurav Sood
Gaurav Sood

Reputation: 690

determine file type/extension of uploaded file in java

i am trying to figure out a way to determine the file type of a file which i upload in my struts2 application. my application can read CSV and XML files and perform operations depending on what type of file was uploaded. i am taking the file as an instance of "File" class. the file is never copied onto the system.

i want to know how to determine the type/content of the uploaded file. i tried the following piece of code to see if i get the file type:

String extension = FilenameUtils.getExtension(file.getAbsolutePath);

logging extension gave me the extension as "tmp". what can i do to get the file extension?

Upvotes: 0

Views: 3294

Answers (5)

Gaurav Sood
Gaurav Sood

Reputation: 690

i found out the solution. as i am using struts, i just had to create a new setter method. If the file object was X, i had to create a setter method

setXFileName(String fileName){
this.xFileName = fileName;
}

struts does the rest

Upvotes: 0

user3159253
user3159253

Reputation: 17455

Check the following library: http://jmimemagic.sourceforge.net/index.html

It should be the one you need. Also you may consider the following review which covers a lot of libraries of that kind.

Actually all modern Unix-like systems have file utility which checks a given file content and report its type according to its database (/etc/magic or /usr/share/file/magic). But this approach involves dependency on an external system functrionality which may be inaccessible for you.

Upvotes: 0

fge
fge

Reputation: 121692

If you use Java 7, you can use Files.probeContentType(). It is not lured by extensions...

The JDK has a number of file formats recognized as a default; this may be enough for you.

Otherwise, well, it is extensible!

Usage:

Files.probeContentType(file.toPath().toAbsolutePath())

Upvotes: 3

Shekhar Khairnar
Shekhar Khairnar

Reputation: 2691

try this:

 public static void main(String[] args) {
    File f = new File("d:/sample.txt");
    System.out.println(getExtention(f.getAbsolutePath()));
}

public static String getExtention(String file){
    if(null == file  || !file.contains(".")){
        return null;
    }else{
        return file.substring(file.lastIndexOf("."));
    }
}

Upvotes: 0

Divya
Divya

Reputation: 1487

you can try to get the extension from this

private String getFileExt(File file) {
String name = file.getName();
try {
    return name.substring(name.lastIndexOf("."));

} catch (Exception e) {
    return "";
}

}

Upvotes: -1

Related Questions