Question

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();
}
Was it helpful?

Solution

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.
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top