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?
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/*">
Feel free to notice me what I may have forgotten, and I'll be happy to include it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With