Java题每日一练 Day17

该博客展示了如何使用Java对图片进行加密和解密操作。通过字节流FileInputStream和BufferedInputStream读取图片,然后利用位运算进行加密,将加密后的数据写入新的文件。解密过程则是通过再次应用位运算来还原图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:将图片进行加密操作

解题思路:将图片进行加密就是按照某种特定操作进行复制的过程,首先要对非文本文件进行读取,用到字节流FileInputStream,由于想提高读取效率,故使用处理流BufferedInputStream将其封装起来,写入时则采用配套的BufferedOutputStream。

package FileStudy;
import java.io.*;
//实现图片的加密和解密操作
public class PicTest {
	public static void main(String[] args) {
	    String sname="C:/Users/0.0/Pictures/6666.jpg";
	    String ename="C:/Users/0.0/Pictures/6777.jpg";
	    String hname="C:/Users/0.0/Pictures/6888.jpg";
	    PicTest.jiami( sname, ename);
	    PicTest.jiami( ename, hname);
	}
	//一、加密
	public static void jiami(String sname,String ename) {
		BufferedInputStream bis=null;
		BufferedOutputStream bos=null;
		try {
			bis = new BufferedInputStream(new FileInputStream(sname));
			bos = new BufferedOutputStream(new FileOutputStream(ename));
			byte[] bs=new byte[10];
			int len;
			while((len=bis.read(bs))!=-1) {
				for(int i=0;i<len;i++) {
					bs[i]=(byte)(bs[i]^5);
				}
				bos.write(bs,0,len);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
		
		    try {
				bis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    try {
				bos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	//二、解密
	public static void jiemi(String ename,String hname) {
		BufferedInputStream bis=null;
		BufferedOutputStream bos=null;
		try {
			bis = new BufferedInputStream(new FileInputStream(ename));
			bos = new BufferedOutputStream(new FileOutputStream(hname));
			byte[] bs=new byte[10];
			int len;
			while((len=bis.read(bs))!=-1) {
				for(int i=0;i<len;i++) {
					bs[i]=(byte)(bs[i]^5^5);
				}
				bos.write(bs,0,len);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
		
		    try {
				bis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    try {
				bos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值