问题描述:

How can I check whether the file version is .gz or .bzip2. I searched in File Java docs but couldn' find any method. Can you please let me know?

My requirement is to show the file on the UI , if .txt doesn't exist then check if .gz exists and if that doesnt exist then check if .bzip2 file exists and hence I am looking to check the extension of the file. I am assuming that I need to be looking at the Type of file.

网友答案:

You may use Files Utility of Guava , and use the method of Files.getFileExtension(String String fullName)

System.out.println(Files.getFileExtension("C:\\fileName.txt"));

The output is:

txt

The source code is pretty simple though,

public static String getFileExtension(String fullName) {
    checkNotNull(fullName);
    String fileName = new File(fullName).getName();
    int dotIndex = fileName.lastIndexOf('.');
    return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
}
网友答案:

Java 7 provides FileTypeDetector#probeContentType(Path) which returns

[...] the string form of the value of a Multipurpose Internet Mail Extension (MIME) content type as defined by RFC 2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. The string must be parsable according to the grammar in the RFC 2045.

If that fails, you don't have many options. You can check the extension (unsafe because a file can have any name) or try to parse it as gz or bzip2 content and whichever succeeds is correct.

网友答案:

You could use:

  • java.io.File.getName() to get the filename and then apply a regular expression
  • java.nio.file.Files.probeContentType()
  • org.apache.commons.io.FilenameUtils.getExtension()
网友答案:

Programmatically determining the type of a file can be surprisingly tricky and there have been many content-based file identification approaches proposed and implemented. There are several implementations available in Java for detecting file types and most of them are largely or solely based on files' extensions

Here is LINK

网友答案:

Try something like this

String extension = "";
int i = fileName.lastIndexOf('.');
if (i >= 0) { extension = fileName.substring(i+1); }

which would produce the extension not including the "." so Notepad.txt this syntax would produce txt --- Or word.docx this syntax would produce docx

相关阅读:
Top