简体   繁体   中英

How to validate file type in java

I have created a text file with some content. I changed its extension to .xlsx. I used this code to validate file-

String filepath = "C:\\Users\\prabhat.sameer\\Desktop\\test.xlsx";
File f = new File(filepath);
String mimetype= new MimetypesFileTypeMap().getContentType(f);
String type = mimetype.split("/")[0];
System.out.println("type " + type);
if (type.equals("text")) {
    System.out.println("It's an text file");
} else {
    System.out.println("It's NOT an text file");
}

Its content type also changed with change of extension. How to validate this?

If you open the file by double-clicking on it, are you able to read the data? Usually a special library like POI is required to write to excel so I would be surprised if it does. If your txt file has data in csv(comma separated) format, then changing the extension to .csv should work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM