2

我正在编写一个程序来从JFileChooser. 如何获取文件类型(例如,该文件是“ .dat ”的“ .txt ”还是“ .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);
}
4

3 回答 3

8

使用String#substringString#lastIndexOf

filename.substring(filename.lastIndexOf("."),filename.length())

于 2013-08-26T08:29:23.923 回答
2

如果你不想splitsubstring,你可以使用Guava 库文件getFileExtention):

String extension = Files.getFileExtension(path);
于 2013-08-26T08:30:05.477 回答
0

我认为这会很有用。

File f = choice.getSelectedFile();
String fileType = choice.getTypeDescription(f);
于 2018-12-10T05:23:45.303 回答