1

To be very clear up front: I do not care what the file extension is, only the actual contents.** I am essentially trying to find a Java implementation of the file command.

I am currently writing an image sorter that converts all my photos to PNG format. To do this, I have to convert my files if they are JPG or Web/P or anything else. I went around Stack Overflow and all the responses were looking at the file extension, which is not what I am interested in. I am trying to use Files.probeContentType(), but (as far as I can tell) only looks at the file extension:

public class Type {

        public static void main(String[] args) throws IOException {

                System.out.println(Files.probeContentType(new File(args[0]).toPath()));

        }

}
bleh@bleh:/tmp$ file png
png: PNG image data, 600 x 600, 8-bit/color RGB, non-interlaced
bleh@bleh:/tmp$ java Type png
null

As stated above, I do not care what the file extension is. I am simply trying to approximate the file command in Java.

I am also open to suggestions of a different programming language entirely (though not bash).

guninvalid
  • 411
  • 2
  • 5
  • 16
  • Your code needs to make a guess based on the file content. This is what the 'file' command in Linux does. Particular file types may make it easy by starting with a 'magic number', but it's still a guess. I'd look at the code for the file command. – passer-by Jan 01 '22 at 01:56

1 Answers1

0

You can use from apache tika, like below :

<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-core -->
<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-core</artifactId>
    <version>2.2.1</version>
</dependency>

Tika tika = new Tika();  
String type = tika.detect(new File("javatpoint.txt"));  
System.out.println("file type : " + type);  
aref behboodi
  • 164
  • 2
  • 11