简体   繁体   English

如何在Java中验证文件类型

[英]How to validate file type in java

I have created a text file with some content. 我创建了一个包含一些内容的文本文件。 I changed its extension to .xlsx. 我将其扩展名更改为.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. 通常需要特殊的库(如POI)才能写入excel,所以如果这样做我会感到惊讶。 If your txt file has data in csv(comma separated) format, then changing the extension to .csv should work for you. 如果您的txt文件包含csv(逗号分隔)格式的数据,则将扩展名更改为.csv应该适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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