当前位置:Gxlcms > 数据库问题 > RandomAccessFile类进行文件加密

RandomAccessFile类进行文件加密

时间:2021-07-01 10:21:17 帮助过:37人阅读

/解密示例。

 

package io;

import java.io.*;

public class encrypt {

    private File file; //存储文件对象信息

    byte[] buf;  //缓冲区,存储文件中的所有数据    RandomAccessFile fp;

    //用参数filename指定的文件构造一个filed对象存储

    //同时为缓冲区buf分配与文件长度相等的存储空间

    public encrypt(String filename){

        file=new File(filename);

        buf=new byte[(int)file.length()];

    }

    

    public encrypt(File destfile){

        file = destfile;

        buf = new byte[(int)file.length()];

    }

    

    //按照读写的方式打开文件

    public void openFile()throws FileNotFoundException{

        fp=new RandomAccessFile(file,"rw");

    }

    

    //关闭文件

    public void closeFile()throws IOException{

        fp.close();

    }

    

    //对文件进行加密/解密

    public void coding()throws IOException{

        //将文件内容读到缓冲区中        fp.read(buf);

        //将缓冲区中的内容取反

        for(int i=0;i<buf.length;i++)

            buf[i]=(byte)(~buf[i]);

        //将文件指针定位到文件头部

        fp.seek(0);

        //将缓冲区中的内容写入到文件中        fp.write(buf);

    }

    

    public static void main(String[] args) {

        encrypt oa;

        if(args.length<1){

            System.out.println("你需要指定加密文件的名字!");

            return;

        }

        try {

            oa = new encrypt(args[0]);

            oa.openFile();

            oa.coding();

            oa.closeFile();

            System.out.println("文件加密成功!");

        } catch (FileNotFoundException e) {

            System.out.println("没有找到文件:"+args[0]);

        }catch (IOException e){

            System.out.println("文件读写错误:"+args[0]);

        }

        

    }

 

}

RandomAccessFile类进行文件加密

标签:exception   读写   dex   length   random   pre   头部   java   out   

人气教程排行