Determining binary/text file type in Java?

前端 未结 10 1142
心在旅途
心在旅途 2020-12-02 16:46

Namely, how would you tell an archive (jar/rar/etc.) file from a textual (xml/txt, encoding-independent) one?

10条回答
  •  清歌不尽
    2020-12-02 17:24

    Using Java 7 Files class http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType(java.nio.file.Path)

    boolean isBinaryFile(File f) throws IOException {
            String type = Files.probeContentType(f.toPath());
            if (type == null) {
                //type couldn't be determined, assume binary
                return true;
            } else if (type.startsWith("text")) {
                return false;
            } else {
                //type isn't text
                return true;
            }
        }
    

提交回复
热议问题