JAVA简单加密-RandomAccessFile应用

package tarena1801.day;

import java.io.FileNotFoundException;

import java.io.RandomAccessFile;

import java.util.Scanner;



public class Test1 {
//加密解密算法:RandomAccessFile应用
public static void main(String[] args) {
System.out.println("请输入文件路径:");
String path=new Scanner(System.in).nextLine();
System.out.println("请输入Key值:");
int key=new Scanner(System.in).nextInt();
try {
encrypt(path,key);//具体实现的操作
System.out.println("完成");
} catch (Exception e) {
System.out.println("失败");
}
}
private static void encrypt(String path, int key) throws Exception {
/*
*1.新建RandomAccessFile实例赋给raf
*2.单字节读取文件字节数据
*3.读到的字节值与key求异或,因为对位异或两次运算会得到原值。
*4.指针移动回前一个位置。即当前位置-1
*  当前位置:raf.getFilePointer();
*5.将异或结果写到文件。
*/
RandomAccessFile raf=new RandomAccessFile(path, "rw");
byte[] buf=new byte[8192];
int n;
while((n=raf.read(buf))!=-1)
{
for (int i = 0; i < n; i++) {
buf[i]^=key;
}
raf.seek(raf.getFilePointer()-n);
raf.write(buf, 0, n);
}
raf.close();
}
}
发布了19 篇原创文章 · 获赞 0 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/ds19920925/article/details/41457331