在java中读取文件的标题 [英] Reading the header of a file in java

查看:248
本文介绍了在java中读取文件的标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有人知道如何使用魔术数字或ascii值读取java中文件的标题以获取文件扩展名?

Does any one know how to read the header of a file in java using "magic numbers" or ascii values to get the name of the extension of a file

推荐答案

也许不是你想要的答案,但是你给我们的信息很少......

Maybe not the answer you wanted, but as you gave us very little information ...

在unixoid系统中(Linux,Mac) ,* BSD)您拥有文件命令,

In unixoid systems (Linux, Mac, *BSD) you have the file command, that


测试每个参数以尝试对其进行分类。按顺序执行三组测试:文件系统测试,魔术测试和语言测试。成功的第一个测试会导致打印文件类型。

tests each argument in an attempt to classify it. There are three sets of tests, performed in this order: filesystem tests, magic tests, and language tests. The first test that succeeds causes the file type to be printed.

例如

$ file linux-image-3.1.0-030100rc10-generic_3.1.0-030100rc10.201110200610_amd64.deb
linux-image-3.1.0-030100rc10-generic_3.1.0-030100rc10.201110200610_amd64.deb: Debian binary package (format 2.0)

使用 Runtime.exec(...)您可以调用该程序并解析其输出。

Using Runtime.exec(...) you could invoke that program and parse its output.

确定给定文件是否为 PNG

import java.io.*;

public class IsPng {

    public static void main(String ...filenames) throws Exception {
        if(filenames.length == 0) {
            System.err.println("Please supply filenames.");
            return;
        }

        for(String filename : filenames) {
            if(isPng(new File(filename))) {
                System.out.println(filename + " is a png.");
            } else {
                System.out.println(filename + " is _not_ a png.");
            }
        }
    }

    private static final int MAGIC[] = new int[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };

    private static boolean isPng(File filename) throws Exception {
        FileInputStream ins = new FileInputStream(filename);
        try {
            for(int i = 0; i < MAGIC.length; ++i) {
                if(ins.read() != MAGIC[i]) {
                    return false;
                }
            }
            return true;
        } finally {
            ins.close();
        }
    }

}



编辑2 :



有时 URLConnection.getContentType()也适用于本地文件:

Edit 2:

Sometimes URLConnection.getContentType() works, too, for local files:

new File(name).toURI().toURL().openConnection().getContentType()

但是您的评论听起来像是必须自己实施该方法,而不是使用外部程序(?)。

But your comments sound like you have to implement the method by yourself, not using external programs (?).

这篇关于在java中读取文件的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆