Java可以通过以下方法来判断文件的类型:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileTypeChecker {
public static void main(String[] args) {
File file = new File("path_to_file");
try {
String fileType = Files.probeContentType(file.toPath());
System.out.println("File type: " + fileType);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.IOException;
import java.net.URLConnection;
public class FileTypeChecker {
public static void main(String[] args) {
File file = new File("path_to_file");
try {
String fileType = URLConnection.guessContentTypeFromName(file.getName());
System.out.println("File type: " + fileType);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.File;
import org.apache.tika.Tika;
public class FileTypeChecker {
public static void main(String[] args) {
File file = new File("path_to_file");
Tika tika = new Tika();
try {
String fileType = tika.detect(file);
System.out.println("File type: " + fileType);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这些方法可以根据不同的需求选择使用,其中Apache Tika库更加全面和准确。