Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check given file is Simple Text File using Java [closed]

Tags:

java

I need to import large text files into database. Structure of that text file is predefine using several separator and all. I just need to check if given file is text file or not (regardless of extension).

How is it possible using Java?

like image 718
Ketan Avatar asked Dec 03 '22 22:12

Ketan


1 Answers

  • In a standalone Java application

    • Java 1.6 or lower (java.io.File)

      File file = new File("/myFolder/myFile");
      InputStream is = new BufferedInputStream(new FileInputStream(file));
      String mimeType = URLConnection.guessContentTypeFromStream(is);
      
    • Java 1.7 or higher (java.nio.file.Path - through installed FileTypeDetector invoked with java.nio.file.Files.probeContentType()

      Path path = FileSystems.getDefault().getPath("myFolder", "myFile");
      String mimeType = Files.probeContentType(path);
      
  • In a framework agnostic web application

    • Use a 3rd party library like JMimeMagic or Apache Tika like described in this answer:

      InputStream is = uploadedFile.getInputStream();
      String mimeType = Magic.getMagicMatch(is, false).getMimeType();
      
  • In a Struts2 web application

    • through Struts2 FileUploadInterceptor.setAllowedTypes()

      <!-- 
          Configured either 
              - globally to a package or 
              - locally to an Action
          in Struts.xml
      -->
      <interceptor-ref name="fileUpload">
          <param name="allowedTypes">image/png,image/gif,image/jpeg</param>
      </interceptor-ref>
      

    More documentation on FileUploadInterceptor and FileUpload

  • Client side in a web application

    • with HTML5's accept attribute of <input type="file" /> (as described in this answer)

      <input type="file" accept="image/*,video/*">
      





I left out all the solutions based on the file extension (that often are not enough reliable) and some alternative 3rd party libraries and older solution.

Feel free to notice me what I may have forgotten, and I'll be happy to include it here.

like image 78
Andrea Ligios Avatar answered Feb 01 '23 11:02

Andrea Ligios