Search code examples
javafilejavafxfileinputstream

JavaFX Button for FileInputStream?


 runEncrypt.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

                File inputFile = new File("/Users/aktasberk/Desktop/hey");
                File encryptedFile = new File("/Users/aktasberk/Desktop/Encrypted_"+inputFile.getName());
                File decryptedFile = new File("/Users/aktasberk/Desktop/Decrypted_"+inputFile.getName());

                try {
                    String key = "16BitKeyIsHere16";
                CryptoUtils.encrypt(key, inputFile, encryptedFile);
                  CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
                } catch (CryptoException ex) {
                  System.out.println(ex.getMessage());
                ex.printStackTrace();
                }
        }
    });

Okay so I have an encryption&decryption project, the encrypting and decrypting works fine but I have some problems using FileInputStream to get the file from directory, I have a browse button to do that but could not make it work, so as you can see in the code I get the input file manually.

Below here is my browse button opening up a file dialog to let me choose a file.

browseEncrypt.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {


            File selectedFile = chooseEncrypt.showOpenDialog(primaryStage);
            if (selectedFile != null) {
                encryptPath.setText(selectedFile.getPath());
                primaryStage.show();
            }
        }
    });

I need to get the file from browse button instead of declaring it manually in the code, I can be more specific if info is needed, thanks.


Solution

  • Delete local:

    File encryptedFile = new File("/Users/aktasberk/Desktop/Encrypted_"+inputFile.getName());
    

    Make global

    File encryptedFile;
    

    Then:

    browseEncrypt.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
    
    
            File selectedFile = chooseEncrypt.showOpenDialog(primaryStage);
            if (selectedFile != null) {
                encryptPath.setText(selectedFile.getPath());
                encryptedFile = selectedFile;//Add This!
                primaryStage.show();//Not sure why this is here?
            }
        }
    });