0

I am trying to Open a file with specific extension ( .fcg or .wtg ) using file Dialog is there a way to do it ??

Dawnlight
  • 179
  • 1
  • 2
  • 11

3 Answers3

2

If you can use JFileChooser you can use JFileChooser.addChoosableFileFilter() to filter files by extension.

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.addChoosableFileFilter(new FileFilter() {

        @Override
        public String getDescription() {
            return "*.fct, *.wtg";
        }

        @Override
        public boolean accept(File f) {
            return f.getName().endsWith(".fcg") ||
            f.getName().endsWith(".wtg");
        }
    });
Bala R
  • 107,317
  • 23
  • 199
  • 210
1

You can use this this code to choose a file and read

public void openFile() throws Exception {
    int rowCount = 0;
    int rowNo = 2;
    String id = "";
    String name = "";
    JFileChooser fc = new JFileChooser();
    int result = fc.showOpenDialog(new JPanel());
    if (result == JFileChooser.APPROVE_OPTION) {
        String file = String.valueOf(fc.getSelectedFile());

        File fil = new File(file);
        System.out.println("File Selected" + file);
        FileInputStream fin = new FileInputStream(fil);
        int ch;
        while ((ch = fin.read()) != -1) {
            System.out.print((char)ch);
        }
    } else {
    }
}
Khoyendra Pande
  • 1,627
  • 5
  • 25
  • 42
0

As this is google search #1 for me, this is the solution which worked best for me:

How to restrict file choosers in java to specific files

specifics:

    JFileChooser open = new JFileChooser(openPath);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("PLSQL Files", "sql", "prc", "fnc", "pks"
                                                                    , "pkb", "trg", "vw", "tps" , "tpb");
    open.setFileFilter(filter);
Community
  • 1
  • 1
Oscorp
  • 13
  • 4