RandomAccessFile类

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());
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值