使用Java中的FileChooser选择后加密文件

时间:2017-07-16 15:16:44

标签: java

对于我的新项目,我尝试在gui中选择文档后对其进行编码。我的程序包含两部分,一部分用于选择文件,另一部分用于编码。因此,在选择文件后,应该调用encrypt方法,但它并不真正起作用,因为似乎没有采用这条路径。

public class frame1 {

    String filepath;

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("Test");
        frame.getContentPane().setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton button = new JButton("Encrypt");
        button.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            JFileChooser fileChooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES","txt", "text");
            fileChooser.setFileFilter(filter);
            int returnValue = fileChooser.showOpenDialog(null);
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                  System.out.println(selectedFile.getAbsolutePath());
                  String filepath = selectedFile.getAbsolutePath(); 

            }
        frame.getContentPane().add(button);
        frame.pack();
        frame.setVisible(true);

      public void encrypt() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
        KeyGenerator keygenerator = KeyGenerator.getInstance("AES");
        SecretKey myDesKey = keygenerator.generateKey();
        Cipher desalgCipher;
        desalgCipher = Cipher.getInstance("AES");
        desalgCipher.init(Cipher.ENCRYPT_MODE, myDesKey);

        Path path = Paths.get(filepath); 
        try(InputStream is = Files.newInputStream(path);       
        CipherInputStream cipherIS = new CipherInputStream(is, desalgCipher);  
        BufferedReader reader = new BufferedReader(new InputStreamReader(cipherIS));){  
            String line;
            while((line = reader.readLine()) != null){
                System.out.println(line);            
            }
        }
       }         
}

1 个答案:

答案 0 :(得分:2)

您可以对程序进行简单的更改,即将选择器返回的文件传递给encrypt()方法。例如:

import javax.crypto.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class App {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);

        JFrame frame = new JFrame("Test");
        frame.getContentPane().setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JButton button = new JButton("Encrypt");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                JFileChooser fileChooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");
                fileChooser.setFileFilter(filter);
                int returnValue = fileChooser.showOpenDialog(null);
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    System.out.println(selectedFile.getAbsolutePath());
                    String filepath = selectedFile.getAbsolutePath();
                    try {
                        encrypt(filepath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            public void encrypt(String path) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
                KeyGenerator keygenerator = KeyGenerator.getInstance("AES");
                SecretKey myDesKey = keygenerator.generateKey();
                Cipher desalgCipher;
                desalgCipher = Cipher.getInstance("AES");
                desalgCipher.init(Cipher.ENCRYPT_MODE, myDesKey);

                try (InputStream is = Files.newInputStream(Paths.get(path));
                     CipherInputStream cipherIS = new CipherInputStream(is, desalgCipher);
                     BufferedReader reader = new BufferedReader(new InputStreamReader(cipherIS));) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println(line);
                    }
                }
            }
        });

        frame.getContentPane().add(button);
        frame.setSize(300, 400);
        frame.setVisible(true);
    }
}