1

Given this method :

public void OutputWrite (BigInteger[] EncryptCodes) throws FileNotFoundException{

    JFileChooser chooser = new JFileChooser();

    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);  
    chooser.showSaveDialog(null);

    String path = chooser.getSelectedFile().getAbsolutePath();

    PrintWriter file = new PrintWriter(new File(path+"EncryptedMessage.txt"));

    for (int i = 0; i <EncryptCodes.length; i++) { 
        file.write(EncryptCodes[i]+ " \r\n");     
    }
    file.close();
}

Ignoring the variable names, what this method does is writes data of EncryptCodes in the txt file generated inside the project folder called EncryptedMessage.txt.

What I need is a method to save that txt file instead of in the project folder , to be saved in a location specified by the user during running (Opens a Save As Dialog Box). I think it can be done by JFilechooser, but I can't get it to work.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user1111726
  • 157
  • 2
  • 8
  • 18

2 Answers2

4

You could add a separate method for getting the save location like so:

private File getSaveLocation() {
   JFileChooser chooser = new JFileChooser();
   chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);  
   int result = chooser.showSaveDialog(this);

   if (result == chooser.APPROVE_OPTION) { 
      return chooser.getSelectedFile();
   } else {
      return null;
   }
}

and then use the result as an argument to the overloaded File constructor that takes a parent/directory argument:

public void writeOutput(File saveLocation, BigInteger[] EncryptCodes)
                 throws FileNotFoundException {

   PrintWriter file = 
        new PrintWriter(new File(saveLocation, "EncryptedMessage.txt"));
   ...
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Yes.. perfect, but the phrase "this" presents an error. method showSaveDialog in class JFileChooser cannot be applied to given types; required: Component found: RSAEncryption reason: actual argument RSAEncryption cannot be converted to Component by method invocation conversion ---- – user1111726 Dec 16 '12 at 21:17
  • Ok, you need a `JFrame` argument there. If you're only using the `JFileChooser` in a console app, you can simply use `null` here. – Reimeus Dec 16 '12 at 21:20
0

like this?

PrintWriter file = new PrintWriter(new File(filePathChosenByUser + "EncryptedMessage.txt"));
Theolodis
  • 4,977
  • 3
  • 34
  • 53