Search code examples
javaswingjfilechooser

How to save a folder instead of a file using jFilechooser?


So basically what i am stuck with is that I have this jFrame where i have two TextAreas and i want the save button to behave in such a way that when i enter save and navigate through the directories and enter some name and press save i want to save a folder which consists of these two files . Here is the code that i am using to save one of those textAreas and hence i have two save buttons to save both , Can someone suggest something so that when i enter save i have both these files inside that folder.

Here is the code i m using:

String content = Area.getText();

 JFileChooser chooser = new JFileChooser();

 chooser.setCurrentDirectory(new File("/home"));

 int retrieval = chooser.showSaveDialog(null);

 if (retrieval == JFileChooser.APPROVE_OPTION) {

    try(FileWriter fw = new FileWriter(chooser.getSelectedFile()+".txt")) {
                fw.write(content.toString());
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }
 }

Solution

  • I have faced this problem before and I came up with this solution :

    String content = Area.getText();
    
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("/home"));
    
    int retrieval = chooser.showSaveDialog(null);
    if (retrieval == JFileChooser.APPROVE_OPTION) {
        try {
           File dir = new File(chooser.getSelectedFile().toString());
           dir.mkdir();
           System.out.println(chooser.getSelectedFile().toString());
           File file = new File(chooser.getSelectedFile().toString()+ "/temp.txt");
    
           if (!file.exists()) {
                file.createNewFile();
           }
    
           FileWriter fw = new FileWriter(file.getAbsoluteFile());
           BufferedWriter bw = new BufferedWriter(fw);
           bw.write(content);
           bw.close();
       }
       catch (Exception ex) {
           ex.printStackTrace();
       }
    }
    

    See what it does is it gets you the exact location of where you made the folder using chooser.getSelectedFile() and then using that you can add a file inside that.