Dynamic file extension filtration using jfilechooser java

720 views Asked by At

I am using FileNameExtensionFilter function to filter file names in jfilechooser but the input parameter for extension is of String type. I want to read all the extensions from a text file. filter is in the constructor and I'm developing a notepad kind of application in Netbeans form. solve this or give some better solution to this problem and i only want to use jfilechooser functionality to select and filter files

Thanks in advance

Here is code.

///////////////FILE FILTER
String str= ""txt","abc","xyz","wxy"; //all extensions from TXTfile

public MainFrame(){
    initComponents();
    fileChooser=new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXTFILES",str,"text");
    fileChooser.setFileFilter(filter);
}

////////////////////////  FILE READER
String readFile() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("ext.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append("\n");
       line = br.readLine();
    }
    return sb.toString();
} finally {
    br.close();
}
1

There are 1 answers

4
Sasi Kathimanda On BEST ANSWER

According to JLS,FileNameExtensionFilter method takes "String... extensions", so you what i suggest modficiations in your code is,

// all extensions from TXTfile
String[] extensions= {"txt","abc","xyz","wxy"}; 

JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXTFILES",extensions);
fileChooser.setFileFilter(filter);

int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " 
+fileChooser.getName(new File("ext.txt")));//or you can use getSelectedFile() that  user has choosen.
    }