0

Can I get file type by content. I have a file with .txt extension but actual content in java of that file (it means it should have .java extension), So how can get correct extension of file by reading its content on the file.

  • You can't! Java source code is also valid text. – Elliott Frisch Dec 19 '18 at 05:01
  • The only way to know for sure is to attempt to compile it, or at least partially parse it according to the Java specification. `.java` files are text files. – Robert Harvey Dec 19 '18 at 05:01
  • Possible duplicate of [How do I get the file extension of a file in Java?](https://stackoverflow.com/questions/3571223/how-do-i-get-the-file-extension-of-a-file-in-java) – Mostafa Solati Dec 19 '18 at 05:02
  • @MostafaSolati: That's not what he's looking for. – Robert Harvey Dec 19 '18 at 05:04
  • Any one can get easily file type by getExtension() method of java.But I want to know file type by there content in the file, not by the extension used in file.Currect File extension is .java but file has .txt, So how can get actual file type by there content.@MostafaSolati – Prashant Shukla Dec 19 '18 at 05:19
  • OK, look at [this file](https://github.com/alibaba/Sentinel/blob/master/sentinel-core/src/main/java/com/alibaba/csp/sentinel/node/ClusterNode.java). Every .java file in this repository (once you skip the comments) begins with the word "package" or "import" at the start of a line. If you check the file for those words, I suspect you'll get a 95 to 99 percent confidence level. If that doesn't work, "public class" should. – Robert Harvey Dec 19 '18 at 05:23
  • You can also try https://tika.apache.org/ – Robert Harvey Dec 19 '18 at 05:32
  • Thaks for answer @RobertHarvey , I already tried tika. – Prashant Shukla Dec 19 '18 at 05:36

0 Answers0