读书人

java算法记要

发布时间: 2012-08-28 12:37:01 作者: rapoo

java算法记录

package com.algorithm;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.security.DigestInputStream;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import org.apache.commons.codec.binary.Hex;public class Algorithm {   public static void main(String args[])   {   //冒泡排序   //sort();   //九九乘法表   //multiplicationTable();   //阶乘   System.out.println(factorial(6));           //md5文件摘要           testMessageDigest();   }     /**    * 计算n的阶乘    * @param n    */   public static int  factorial(int n)   {    if(n>1)    {    return n*factorial(n-1);    }    return 1;   }   /**    * 九九乘法表    */   public static void multiplicationTable()   {   for(int i=1;i<10;i++)   {   for(int j=1;j<=i;j++)   {   System.out.print(j+"*"+i+"="+j*i+"\t");   }   System.out.println("\n");   }   }   /**    * 冒泡排序(升序)    */   public static void sort()   {   int a[]={2,3,1,6,90,89,50};   for(int i=0;i<a.length;i++)   {   for(int j=a.length-1;j>i;j--)   {   int tmp=0;   if(a[i]>a[j])   {   tmp=a[j];   a[j]=a[i];   a[i]=tmp;   }   }   }   for(int i=0;i<a.length;i++)   System.out.println(a[i]);   }  /**    * md5文件校验    * @return    * @throws NoSuchAlgorithmException    * @throws IOException    */   public static String testMessageDigest() throws NoSuchAlgorithmException, IOException   {   //文件路径   String filePath="d:\\commons-codec-1.6-bin.zip";   //构建文件输入流   FileInputStream fis=new FileInputStream(new File(filePath));   //初始化MessageDigest,并指定md5算法   DigestInputStream dis=new DigestInputStream(fis,MessageDigest.getInstance("MD5"));   //流缓冲大小   int buf=1024;   //缓冲字节数组   byte[] buffer=new byte[buf];   //读取字节数组并更新摘要,如果更新摘要功能开启的话(默认开启)   while((dis.read(buffer,0,buf))>-1)   {   dis.read(buffer,0,buf);   }   //关闭流   dis.close();   //获得MessageDigest   MessageDigest md=dis.getMessageDigest();   //摘要处理   byte[] b=md.digest();   //十六进制转换   String md5Hex=Hex.encodeHexString(b);   System.out.println(md5Hex.equals("b9ff59c674928d0250f4a0b30c438974"));   //十六进制转换   return md5Hex;   }}


附件中为apache算法包commons-codec-1.6.jar

读书人网 >编程

热点推荐