如何在Java中选择文件输出路径

时间:2019-02-05 13:22:38

标签: java

我正在开发此加密代码,问题是一旦我选择了对该文件进行加密和加密,该文件将保存在默认的net bean项目文件夹中,并且所有具有类似名称的加密文件都将保存。我希望能够选择文件位置并重命名加密输出,我们将不胜感激。

这是部分代码的示例

JFileChooser chooser = new JFileChooser();
    chooser.showOpenDialog(null);
    File f = chooser.getSelectedFile();
    file_path.setText(f.getAbsolutePath());
}                                        

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    try{
        FileInputStream file = new FileInputStream(file_path.getText());
        FileOutputStream outStream = new FileOutputStream("Encrypt.mp4");
        byte k[]="Crot2116MpFr5252".getBytes();
        SecretKeySpec key = new SecretKeySpec(k, "AES");
        Cipher enc = Cipher.getInstance("AES");
        enc.init(Cipher.ENCRYPT_MODE, key);
        CipherOutputStream cos = new CipherOutputStream(outStream, enc);
        byte[] buf = new byte[1024];
        int read;
        while((read=file.read(buf))!=-1){
            cos.write(buf,0,read);
        }
        file.close();
        outStream.flush();
        cos.close();
        JOptionPane.showMessageDialog(null, "The Video file was encrypted Successfully");
    }catch(Exception e){
        JOptionPane.showMessageDialog(null, "Invalid selection");
    }
}                                        

1 个答案:

答案 0 :(得分:0)

您应在FileOutputStream上指定完整路径:

    FileOutputStream outStream = new FileOutputStream("/path/to/file");

此处使用的是绝对路径(文件系统管理器的根路径)。 您也可以使用项目的相对路径,而无需放置第一个/

    FileOutputStream outStream = new FileOutputStream("path/to/file");

像这样,文件将保存在src/main/path/to/file中。