Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通过JFileChooser获取所选文件的类型_Java_Swing_Jfilechooser - Fatal编程技术网

Java 通过JFileChooser获取所选文件的类型

Java 通过JFileChooser获取所选文件的类型,java,swing,jfilechooser,Java,Swing,Jfilechooser,我正在编写一个程序,从JFileChooser中选择文件。如何获取文件类型(例如,该文件是“.txt”还是“.dat”的“.html”等) 我有以下代码。我应该添加什么额外的行 JFileChooser choice = new JFileChooser(); int option = choice.showOpenDialog(this); if (option == JFileChooser.APPROVE_OPTION) { String path=choice.getSelec

我正在编写一个程序,从
JFileChooser
中选择文件。如何获取文件类型(例如,该文件是“.txt”还是“.dat”的“.html”等)

我有以下代码。我应该添加什么额外的行

JFileChooser choice = new JFileChooser();
int option = choice.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION)
{
     String path=choice.getSelectedFile().getAbsolutePath();
     String filename=choice.getSelectedFile().getName();
     System.out.println(path);
     listModel.addElement(path);
     System.out.println(filename);
}
使用和:


filename.substring(filename.lastIndexOf(“.”,filename.length())

如果不希望拆分
子字符串,可以使用():


我认为这将是有用的

File f = choice.getSelectedFile();
String fileType = choice.getTypeDescription(f);

如果您只是想要扩展名:由于您有文件名,只需从文件名字符串中选择所有字符,包括最后一个点。这有很大帮助,并使用标准字符串对象来解决问题,而不需要外部库。非常感谢。
File f = choice.getSelectedFile();
String fileType = choice.getTypeDescription(f);