Java 过滤文件
我想检查文件的文件类型。我想到了神奇的数字,但如何使用它呢 使用Java 我想只允许文本文件和过滤器文件,如jpg等在我的程序。 一些想法,我能做些什么Java 过滤文件,java,Java,我想检查文件的文件类型。我想到了神奇的数字,但如何使用它呢 使用Java 我想只允许文本文件和过滤器文件,如jpg等在我的程序。 一些想法,我能做些什么 private String path; private String fileText; private String textLine; public LoadModel(String path) { this.path = path; this.fileText = ""; FileReader read =
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");
}
}
您可以通过代码示例找到可用于在java中标识mime类型的API列表
在Java7中,也有一个选项
Files.probeContentType(path)
.您可以尝试
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以了解更多详细信息如果您需要您的代码在早期版本的JDK(而不是JDK7)上工作,您可以使用ApacheTika的
MimeType
检测器,它具有MimeType#detect()
方法
更多信息使用String.endsWith(“.ext”)
按文件扩展名(如.jpg)检查文件扩展名是否有任何困难/问题?问题是,您可以将picture.jpg重命名为picture.txt,然后这种方法将不起作用。请注意,在Mac上尚未实现probeContentType: