用一个值,对每个字节值求异或
package com.google.basics;
import java.io.File;
import java.io.RandomAccessFile;
public class Test {
public static void main(String[] args) {
File file = new File("C:\\Users\\HD\\Desktop\\test.txt");
int key=2;
try { encrypt(file, key); System.out.println("完成"); } catch (Exception e) { System.out.println("失败"); e.printStackTrace(); }
}
private static void encrypt(
File file, int key) throws Exception {
/*
* 从文件读取一个字节值,
* 对key异或后,再写回到文件
*/
RandomAccessFile raf =
new RandomAccessFile(file, "rw");
//单字节读取标准格式
//int b;
//while((b = raf.read()) != -1) {
// b ^= key;//异或加密、解密
// //下标往前挪回一位
// raf.seek(raf.getFilePointer()-1);
// //字节值写回到文件
// raf.write(b);
//}
//一般用8k 8192
byte[] buff = new byte[8192];
int n;//保存每一批的数量
while((n = raf.read(buff)) != -1) {
//对数组前n个字节值加密
for(int i=0;i<n;i++) {
buff[i] ^= key;
}
//下标前移n个位置
raf.seek(raf.getFilePointer()-n);
//数组中前n个字节,一批写回文件
raf.write(buff,0,n);
}
raf.close();
}
}