I have to save an excel file with .xls extension.I want that the extension should be taken by default as soon as I select the file type in save file dialog box designed using file chooser.I have tried this much of code but it is saving the file in .xls format only when I give the file name as filename.xls
public void FileSave() throws IOException{
JFileChooser chooser=new JFileChooser(".");
FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files","xls","excel");
chooser.addChoosableFileFilter(filter);
chooser.setFileFilter(filter);
chooser.setFileSelectionMode(chooser.FILES_AND_DIRECTORIES);
chooser.setDialogTitle("Save File");
chooser.setCurrentDirectory(new File(System.getProperties().getProperty("user.home")));
chooser.setFileFilter(new javax.swing.filechooser.FileFilter(){
public boolean accept(final File f){
return f.isDirectory()|| file.getAbsolutePath().endsWith(".xls");
}
public String getDescription(){
return "Excel files (*.xls)";
}
});
int returnVal1=chooser.showSaveDialog(this);
if (returnVal1 == JFileChooser.APPROVE_OPTION){
file1 = chooser.getSelectedFile();
if(!file1.exists()){
FileOutputStream fileOut = new FileOutputStream(file1);
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
}
else if(file1.exists()){
int res=JOptionPane.showConfirmDialog(this,"File already exists.Do you wish to overwrite?");
if(res == JOptionPane.YES_OPTION){
FileOutputStream fileOut = new FileOutputStream(file1);
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
}else if(res == JOptionPane.NO_OPTION){
int returnVal2=chooser.showSaveDialog(this);
if (returnVal2 == JFileChooser.APPROVE_OPTION){
File file2 = chooser.getSelectedFile();
if(!file2.exists()){
FileOutputStream fileOut = new FileOutputStream(file2);
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
}
}
}else if (res == JOptionPane.CANCEL_OPTION){
JOptionPane.showMessageDialog(this, "User cancelled operation.");
}
}
}
}