Java Swing How to - Open Selected file with default application in JFileChooser








Question

We would like to know how to open Selected file with default application in JFileChooser.

Answer

import java.awt.Desktop;
import java.io.File;
/*  w  ww .j  av a2  s .c o m*/
import javax.swing.JFileChooser;

public class Main {
  public static void main(String[] args) throws Exception{
    JFileChooser fileChooser = new JFileChooser();
    int a = fileChooser.showOpenDialog(null);

    if (a == JFileChooser.APPROVE_OPTION) {
      File fileToOpen = fileChooser.getSelectedFile();
      Desktop.getDesktop().open(fileToOpen);
    }
  }
}