过滤文件

时间:2013-01-17 10:51:38

标签: java

我想检查文件的文件类型。我想过魔术数字,但是如何使用它 用Java。

我想在我的程序中只允许Textfiles和过滤文件,如jpg等。 一些想法,我能做些什么。

private String path;
private String fileText;
private String textLine;
public LoadModel(String path) {

    this.path = path;
    this.fileText = "";

    FileReader read = null;
    BufferedReader bufRead = null;

    if (path != null && new File(path).exists()
            && !(new File(path).isDirectory())) {


        try {

            read = new FileReader(path);

            bufRead = new BufferedReader(read);
            do {
                try {
                    this.textLine = bufRead.readLine();
                } catch (IOException ex) {
                    Logger.getLogger(LoadModel.class.getName()).log(Level.SEVERE, null, ex);
                }
                if (this.textLine != null) {
                    this.fileText = this.fileText + this.textLine + "\n";
                }
            } while (this.textLine != null);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(LoadModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        HinweisDialogController.hinweisDialogOK("Die angegebene Datei existiert nicht");

    }
}

3 个答案:

答案 0 :(得分:5)

Here您可以在java中找到可用于识别mime类型的API列表,其中包含代码示例。

同样在java 7中有一个选项

Files.probeContentType(path)

答案 1 :(得分:2)

您可以尝试java.nio.file.Files.probeContentType来确定文件内容类型。例如这个测试

    System.out.println(Files.probeContentType(Paths.get("1.xml")));
    System.out.println(Files.probeContentType(Paths.get("1.txt")));

打印

text/xml
text/plain

请参阅API以获取更多详细信息

答案 2 :(得分:0)

如果您需要使用代码来处理早期版本的JDK(而不是JDK7),可以使用Apache Tika's MimeType检测器,它具有MimeType#detect()方法

更多信息here

相关问题