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);