经典 读取文件 附件des加密(短而精)

 

  1. package com.spring.sky.util;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.InputStreamReader;  
  11. import java.io.OutputStream;  
  12. import java.security.Key;  
  13.   
  14. import javax.crypto.Cipher;  
  15. import javax.crypto.CipherInputStream;  
  16. import javax.crypto.spec.SecretKeySpec;  
  17.   
  18. import org.apache.http.entity.InputStreamEntity;  
  19.   
  20. /*** 
  21.  * DES文件加密&解密  <br> 
  22.  * 可以实现Android和window的文件互通  
  23.  * @author spring.sky 
  24.  * Email:[email protected] 
  25.  * QQ:840950105 
  26.  * 
  27.  */  
  28. public class FileDES {  
  29.     /**加密解密的key*/  
  30.     private Key mKey;  
  31.     /**解密的密码*/  
  32.     private Cipher mDecryptCipher;  
  33.     /**加密的密码*/  
  34.     private Cipher mEncryptCipher;  
  35.     public FileDES(String key) throws Exception  
  36.     {  
  37.         initKey(key);  
  38.         initCipher();  
  39.     }  
  40.       
  41.     /** 
  42.      * 创建一个加密解密的key 
  43.      * @param keyRule  
  44.      */  
  45.     public void initKey(String keyRule) {  
  46.         byte[] keyByte = keyRule.getBytes();  
  47.         // 创建一个空的八位数组,默认情况下为0   
  48.         byte[] byteTemp = new byte[8];  
  49.         // 将用户指定的规则转换成八位数组   
  50.         for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {  
  51.             byteTemp[i] = keyByte[i];  
  52.         }  
  53.         mKey = new SecretKeySpec(byteTemp, "DES");  
  54.     }  
  55.       
  56.     /*** 
  57.      * 初始化加载密码 
  58.      * @throws Exception 
  59.      */  
  60.     private void initCipher() throws Exception  
  61.     {  
  62.         mEncryptCipher = Cipher.getInstance("DES");  
  63.         mEncryptCipher.init(Cipher.ENCRYPT_MODE, mKey);  
  64.           
  65.         mDecryptCipher = Cipher.getInstance("DES");  
  66.         mDecryptCipher.init(Cipher.DECRYPT_MODE, mKey);  
  67.     }  
  68.       
  69.     /** 
  70.      * 加密文件 
  71.      * @param in 
  72.      * @param savePath 加密后保存的位置 
  73.      */  
  74.     public void doEncryptFile(InputStream in,String savePath)  
  75.     {  
  76.         if(in==null)  
  77.         {  
  78.             System.out.println("inputstream is null");  
  79.             return;  
  80.         }  
  81.         try {  
  82.             CipherInputStream cin = new CipherInputStream(in, mEncryptCipher);  
  83.             OutputStream os = new FileOutputStream(savePath);  
  84.             byte[] bytes = new byte[1024];  
  85.             int len = -1;  
  86.             while((len=cin.read(bytes))>0)  
  87.             {  
  88.                 os.write(bytes, 0, len);  
  89.                 os.flush();  
  90.             }  
  91.             os.close();  
  92.             cin.close();  
  93.             in.close();  
  94.             System.out.println("加密成功");  
  95.         } catch (Exception e) {  
  96.             System.out.println("加密失败");  
  97.             e.printStackTrace();  
  98.         }  
  99.     }  
  100.       
  101.     /** 
  102.      * 加密文件 
  103.      * @param filePath 需要加密的文件路径 
  104.      * @param savePath 加密后保存的位置 
  105.      * @throws FileNotFoundException  
  106.      */  
  107.     public void doEncryptFile(String filePath,String savePath) throws FileNotFoundException  
  108.     {  
  109.         doEncryptFile(new FileInputStream(filePath), savePath);  
  110.     }  
  111.       
  112.       
  113.     /** 
  114.      * 解密文件 
  115.      * @param in 
  116.      */  
  117.     public void doDecryptFile(InputStream in)  
  118.     {  
  119.         if(in==null)  
  120.         {  
  121.             System.out.println("inputstream is null");  
  122.             return;  
  123.         }  
  124.         try {  
  125.             CipherInputStream cin = new CipherInputStream(in, mDecryptCipher);  
  126.             BufferedReader reader = new BufferedReader(new InputStreamReader(cin)) ;  
  127.             String line = null;  
  128.             while((line=reader.readLine())!=null)  
  129.             {  
  130.                 System.out.println(line);  
  131.             }  
  132.             reader.close();  
  133.             cin.close();  
  134.             in.close();  
  135.             System.out.println("解密成功");  
  136.         } catch (Exception e) {  
  137.             System.out.println("解密失败");  
  138.             e.printStackTrace();  
  139.         }  
  140.     }  
  141.     /** 
  142.      * 解密文件 
  143.      * @param filePath  文件路径 
  144.      * @throws Exception 
  145.      */  
  146.     public void doDecryptFile(String filePath) throws Exception  
  147.     {  
  148.         doDecryptFile(new FileInputStream(filePath));  
  149.     }  
  150.       
  151.       
  152.     public static void main(String[] args)throws Exception {  
  153.         FileDES fileDES = new FileDES("spring.sky");  
  154.         fileDES.doEncryptFile("d:/a.txt""d:/b");  //加密   
  155.         fileDES.doDecryptFile("d:/b"); //解密   
  156.     }  
  157.       
  158. }  

上面的代码,我分别在Android 1.6和java平台上面测试通过了,没任何问题的,只是根据不同的需求做一下封装,希望对大家有帮忙,让大家少走弯路!

 

package com.ppmeet;  

  

import java.io.File;  

import java.io.FileInputStream;  

import java.io.FileOutputStream;  

import java.io.IOException;  

import java.io.InputStream;  

  

import org.apache.http.util.EncodingUtils;  

  

import android.content.Context;  

  

/** 

 * class name:FileService<BR> 

 * class description:android文件的一些读取操作<BR> 

 * PS: <BR> 

 *  

 * @version 1.00 2010/10/21 

 * @author CODYY)peijiangping 

 */  

public class FileService {  

    private Context context;  

  

    public FileService(Context c) {  

        this.context = c;  

    }  

  

    // 读取sd中的文件  

    public String readSDCardFile(String path) throws IOException {  

        File file = new File(path);  

        FileInputStream fis = new FileInputStream(file);  

        String result = streamRead(fis);  

        return result;  

    }  

  

    // 在res目录下建立一个raw资源文件夹,这里的文件只能读不能写入。。。  

    public String readRawFile(int fileId) throws IOException {  

        // 取得输入流  

        InputStream is = context.getResources().openRawResource(fileId);  

        String result = streamRead(is);// 返回一个字符串  

        return result;  

    }  

  

    private String streamRead(InputStream is) throws IOException {  

        int buffersize = is.available();// 取得输入流的字节长度  

        byte buffer[] = new byte[buffersize];  

        is.read(buffer);// 将数据读入数组  

        is.close();// 读取完毕后要关闭流。  

        String result = EncodingUtils.getString(buffer, "UTF-8");// 设置取得的数据编码,防止乱码  

        return result;  

    }  

  

    // 在assets文件夹下的文件,同样是只能读取不能写入  

    public String readAssetsFile(String filename) throws IOException {  

        // 取得输入流  

        InputStream is = context.getResources().getAssets().open(filename);  

        String result = streamRead(is);// 返回一个字符串  

        return result;  

    }  

  

    // 往sd卡中写入文件  

    public void writeSDCardFile(String path, byte[] buffer) throws IOException {  

        File file = new File(path);  

        FileOutputStream fos = new FileOutputStream(file);  

        fos.write(buffer);// 写入buffer数组。如果想写入一些简单的字符,可以将String.getBytes()再写入文件;  

        fos.close();  

    }  

  

    // 将文件写入应用的data/data的files目录下  

    public void writeDateFile(String fileName, byte[] buffer) throws Exception {  

        byte[] buf = fileName.getBytes("iso8859-1");  

        fileName = new String(buf, "utf-8");  

        // Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND  

        // Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。  

        // Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。  

        // MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。  

        // 如果希望文件被其他应用读和写,可以传入:  

        // openFileOutput("output.txt", Context.MODE_WORLD_READABLE +  

        // Context.MODE_WORLD_WRITEABLE);  

        FileOutputStream fos = context.openFileOutput(fileName,  

                Context.MODE_APPEND);// 添加在文件后面  

        fos.write(buffer);  

        fos.close();  

    }  

  

    // 读取应用的data/data的files目录下文件数据  

    public String readDateFile(String fileName) throws Exception {  

        FileInputStream fis = context.openFileInput(fileName);  

        String result = streamRead(fis);// 返回一个字符串  

        return result;  

    }  

}  

 

 

 

你可能感兴趣的:(两天搜索)