Pergunta

I am developing a checksum generator application. I, for now, designed it to give SHA/MD5 output of strings values. I would like to know if you can import files so it can act as an integrity checker too by creating hash values for imported files. Thanks.

Foi útil?

Solução 2

I suppose you need something like that to deal with files:

import org.apache.commons.codec.binary.Hex;

import javax.swing.*;
import java.io.*;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Application {
    public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
        JFileChooser chooser = new JFileChooser();
        int result = chooser.showOpenDialog(null);
        if (JFileChooser.APPROVE_OPTION == result){
            File file = chooser.getSelectedFile();
            MessageDigest digest = MessageDigest.getInstance("MD5");
            try (InputStream is = new FileInputStream(file)) {
                DigestInputStream dis = new DigestInputStream(new BufferedInputStream(is), digest);
                while (dis.read() != -1){}
            }
            JOptionPane.showMessageDialog(null, Hex.encodeHexString(digest.digest()));
        }
    }
}

The point is that files may be quite large, so you should not read full file contents into memory. This implementation streams the file, so it hasn't got large memory footprint. It also demonstrates how to use JFileChooser to acomplish the task.

Outras dicas

are u looking for something like this

FileDialog fd = new FileDialog(parent, "Choose a file", FileDialog.LOAD);
fd.setDirectory("C:\\");
fd.setFile("*.java");
fd.setVisible(true);
String filename = fd.getFile();
if (filename == null)
  System.out.println("file not selected");
else
  System.out.println("You chose " + filename);

you can also use JFileChooser

Using JFileChooser

    JFileChooser fileDlg = new JFileChooser();
    fileDlg.showOpenDialog(this);
    String filename = fileDlg.getSelectedFile().getAbsolutePath();
    jTextField1.setText(filename);

    FileInputStream fis = new FileInputStream(filename);
    byte buffer[] = new byte[fis.available()];
    fis.read(buffer);
    String message = new String(buffer);
    jTextArea1.setText(message);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top