1. 效果图
1.1 原文件内容
1.2 加密后
1.3 解密后
2. Java代码
package com.example.demo.file;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
/**
* @Description 随机存取文件
* @author 大都督
* @date 2018年12月24日
*/
public class RandomAccessFileTest {
public static void main(String[] args) throws FileNotFoundException {
//对文件内容进行加密
// encryptionFile("F:/lee/test/file_test", "RandomAccessFileTest.txt");
//对文件内容进行解密
decryptFile("F:/lee/test/file_test", "RandomAccessFileTest.txt");
}
/**
* @Title: decryptFile
* @Description: 对文件内容进行解密
* @param filePath
* @param fileName
* @author 大都督
* @date 2018年12月24日
* @return void
* @throws FileNotFoundException
*/
private static void decryptFile(String filePath, String fileName) throws FileNotFoundException {
//创建文件对象
File file = new File(filePath, fileName);
//创建字节数组用来暂存解密后的字节
byte[] bt = new byte[(int)file.length()];
//创建文件的randomAccessFile对象
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
try {
//将文件中的内容全部读到字节数组中
randomAccessFile.read(bt);
for (int i=0; i<bt.length; i++) {
//对每个字节减7,来进行解密
bt[i] = (byte)(bt[i]-7);
}
randomAccessFile.setLength(0);
randomAccessFile.write(bt);
//移动文件指针
randomAccessFile.seek(3);
//将其中的一个字节以字符的形式输出
System.out.println((char)randomAccessFile.read());
} catch (Exception e) {
//打印异常消息
System.out.println(e.getMessage());
}
}
/**
* @Title: encryptionFile
* @Description: 对文件内容进行加密
* @param filePath
* @param fileName
* @author 大都督
* @date 2018年12月24日
* @return void
* @throws FileNotFoundException
*/
private static void encryptionFile(String filePath, String fileName) throws FileNotFoundException {
//创建文件对象
File file = new File(filePath, fileName);
//创建字节数组用来暂存加密后的字节
byte[] bt = new byte[(int)file.length()];
//创建文件的randomAccessFile对象
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
try {
//将文件中的内容全部读到字节数组中
randomAccessFile.read(bt);
for (int i=0; i<bt.length; i++) {
//对每个字节加7,来进行加密
bt[i] = (byte)(bt[i]+7);
}
randomAccessFile.setLength(0);
randomAccessFile.write(bt);
//移动文件指针
randomAccessFile.seek(3);
//将其中的一个字节以字符的形式输出
System.out.println((char)randomAccessFile.read());
} catch (Exception e) {
//打印异常消息
System.out.println(e.getMessage());
}
}
}