做文件传输的时候,为了保证文件是合法的有效的,经常会对文件做MD5校验,以确保和原始的文件是一样的.并且做断点续传的时候这一点也是挺重要的,其实JAVA处理这方面也挺不错的,可是我搜了半天,也没有搜到一个用JAVA写的文件MD5生成程序,有的也只是命令行模式下的,没有一个GUI模式的,所以就写了一个GUI的,方便使用,只用了两个类,一个是工具类,除了生成MD5外还可以生成SHA码,大家可以通过改源文件达到这一点,并且文件支持拖放,可以把要生成的文件拖到文本区,就可以显示这个文件的信息了.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JProgressBar;
/**
*
* @author hadeslee
*/
public final class Util {
/**
* 得到文件的MD5码,用于校验
* @param file
* @param jpb
* @return
*/
public static String getMD5(File file, JProgressBar jpb) {
FileInputStream fis = null;
jpb.setMaximum((int) file.length());
jpb.setValue(0);
jpb.setString("正在计算:" + file.getName() + "的MD5值");
try {
MessageDigest md = MessageDigest.getInstance("MD5");
fis = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length = -1;
System.out.println("开始算");
int value = 0;
while ((length = fis.read(buffer)) != -1) {
md.update(buffer, 0, length);
value += length;
jpb.setValue(value);
}
System.out.println("算完了");
return bytesToString(md.digest());
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
return null;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
*
* @param file
* @return
*/
public static String getMD5(File file) {
FileInputStream fis = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
fis = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length = -1;
System.out.println("开始算");
while ((length = fis.read(buffer)) != -1) {
md.update(buffer, 0, length);
}
System.out.println("算完了");
return bytesToString(md.digest());
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
return null;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* 得到文件的SHA码,用于校验
* @param file
* @return
*/
public static String getSHA(File file) {
FileInputStream fis = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA");
fis = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length = -1;
System.out.println("开始算");
while ((length = fis.read(buffer)) != -1) {
md.update(buffer, 0, length);
}
System.out.println("算完了");
return bytesToString(md.digest());
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
return null;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
*
* @param file
* @param jpb
* @return
*/
public static String getSHA(File file,JProgressBar jpb) {
FileInputStream fis = null;
jpb.setMaximum((int) file.length());
jpb.setValue(0);
jpb.setString("正在计算:" + file.getName() + "的MD5值");
try {
MessageDigest md = MessageDigest.getInstance("SHA");
fis = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length = -1;
System.out.println("开始算");
int value=0;
while ((length = fis.read(buffer)) != -1) {
md.update(buffer, 0, length);
value+=length;
jpb.setValue(value);
}
System.out.println("算完了");
return bytesToString(md.digest());
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
return null;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static String bytesToString(byte[] data) {
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f'};
char[] temp = new char[data.length * 2];
for (int i = 0; i < data.length; i++) {
byte b = data[i];
temp[i * 2] = hexDigits[b >>> 4 & 0x0f];
temp[i * 2 + 1] = hexDigits[b & 0x0f];
}
return new String(temp);
}
public static void main(String[] args) {
String s = System.getProperties().getProperty("java.io.tmpdir");
System.out.println(s);
}
}
窗体的代码:
/*
* Main.java
*
* Created on 2007年11月8日, 上午9:15
*/
package test1;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
/**
*
* @author hadeslee
*/
public class Main extends javax.swing.JFrame implements DropTargetListener {
private JFileChooser jfc;
private File toMd5;
private DropTarget dt;
/** Creates new form Main */
public Main() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exe) {
exe.printStackTrace();
}
initComponents();
initOther();
this.setLocationRelativeTo(null);
}
private void initOther() {
dt = new DropTarget(jTextArea1, DnDConstants.ACTION_COPY_OR_MOVE, this);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jpb = new javax.swing.JProgressBar();
jLabel2 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("MD5生成");
setResizable(false);
jLabel1.setText("文件路径:");
jTextField1.setEditable(false);
jButton1.setText("浏览");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder("文件信息"));
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton2.setText("生成");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("退出");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel2.setText("MD5值:");
jTextField2.setEditable(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jpb, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField2))
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)))
.addContainerGap(16, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jButton3)
.addComponent(jpb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(267, 267, 267)
.addComponent(jButton2)
.addGap(10, 10, 10))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (jfc == null) {
jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
}
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
toMd5 = jfc.getSelectedFile();
jTextField1.setText(toMd5.toString());
showFileInfo();
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jButton2.setEnabled(false);
new Thread(){
public void run(){
String s=Util.getMD5(toMd5, jpb);
jTextField2.setText(s);
jButton2.setEnabled(true);
}
}.start();
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void showFileInfo() {
if (toMd5 != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
File f = toMd5;
StringBuilder sb = new StringBuilder();
sb.append("文件名称:").append(f.getName()).append('\n');
sb.append("文件大小:").append(f.length()).append('\n');
sb.append("文件最后修改日期:").append(sdf.format(new Date(f.lastModified()))).append("\n");
sb.append("文件属性:").append(f.canWrite() ? "读写" : "只读").append('\n');
jTextArea1.setText(sb.toString());
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JProgressBar jpb;
// End of variables declaration
public void dragEnter(DropTargetDragEvent dtde) {
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
public void dragOver(DropTargetDragEvent dtde) {
}
public void dropActionChanged(DropTargetDragEvent dtde) {
}
public void dragExit(DropTargetEvent dte) {
}
public void drop(DropTargetDropEvent e) {
try {
if (e.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
Transferable tr = e.getTransferable();
e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
@SuppressWarnings("unchecked")
java.util.List<File> list = (java.util.List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor);
if (list.size() == 1) {
File f = list.get(0);
if (f.isFile()) {
toMd5 = list.get(0);
this.showFileInfo();
jTextField1.setText(toMd5.toString());
}
}
e.dropComplete(true);
}else {
e.rejectDrop();
}
} catch ( IOException io) {
io.printStackTrace();
e.rejectDrop();
} catch ( UnsupportedFlavorException ufe) {
ufe.printStackTrace();
e.rejectDrop();
}
}
}
可以
点击这里下载可执行的JAR文件和源代码
尽管千里冰封
依然拥有晴空
你我共同品味JAVA的浓香.
posted on 2007-11-08 10:11
千里冰封 阅读(7809)
评论(8) 编辑 收藏 所属分类:
JAVASE