JavaFX 2.2 Get selected file extension

IndexOutOfDevelopersException picture IndexOutOfDevelopersException · Dec 17, 2013 · Viewed 9.8k times · Source

I don't know how to get selected file exstesion. I have seen that developers ask this question frequently, but I could find and proper answer. I know it is a bug (fhttp://javafx-jira.kenai.com/browse/RT-18836), but anyway is there any solutions. So I wanna save my linechart as pdf or png. My code for both files works fine. But I just can't stand not to get selected file. Is there any sollution possible. I see that Java has built in function for this issue.

This solution is not relevant for me: JavaFX FileChooser not returning file extension for Windows

My code is:

 FileChooser fileChooser = new FileChooser();
 FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PDF file(*.pdf)" ,"      
 *.pdf");

 fileChooser.getExtensionFilters().add(extFilter);
 extFilter = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.png");
 fileChooser.getExtensionFilters().add(extFilter);
 fileChooser.setTitle("Save as");
 File file = fileChooser.showSaveDialog(primaryStage);

Then I get file path without extensions:

 String filePath = file.getAbsolutePath();

Answer

Shreyas Dave picture Shreyas Dave · Dec 18, 2013

If you want to know the extension of selected file from file chooser here is a code..

String fileName = file1.getName();          
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1, file1.getName().length());
System.out.println(">> fileExtension" + fileExtension);

And here is a brief of what you need to do with file chooser,

FileChooser fileChooser = new FileChooser();
// Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Image Files", "*.jpg", "*.jpeg");
fileChooser.getExtensionFilters().add(extFilter);

File file = fileChooser.showOpenDialog(root.getScene().getWindow());

if (file != null) {

String fileName = file.getName();           
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1, file.getName().length());
System.out.println(">> fileExtension" + fileExtension);

}