java字节流加密_Java—字节流

本文深入讲解Java中的IO流概念及应用,包括输入流与输出流的基本操作,如FileInputStream与FileOutputStream的使用方法,并演示了如何实现文件复制及加密。

一、IO原理

2a29a80c086401b1a2c4ea344d16a64e.png

二、输入流/读操作(InputStream)

1.输入流:从持久性数据存储的硬盘中读取到内存中

2.字节输入流:FileInputStream

3.read() :一个字节一个字节的读取,效率低

4.read(byte[] b):通过设置容器的上限,读取一定量的字节数

public class FileInputStreamDemo {

public static void main(String[] args) throws IOException {

File file = new File("e:/file.txt");

// 创建输入流,完成读操作

InputStream fis = new FileInputStream(file);

// 读取内容

// 方式一:使用read(),每次只能读取一个字符

/*int ch = 0;

while((ch = fis.read()) != -1){

System.out.print((char) ch);

}*/

// 方式二:使用read(byte[] b)

// 创建一个字符数组

byte[] b = new byte[1024];// 定义成1024的整数倍

int len = 0;

while((len = fis.read(b)) != -1){

// new String(字节数组, 起始位置, 长度)

System.out.println(new String(b, 0 , len));

}

// 关闭资源

fis.close();

}

}

三、输出流/写操作(OutputStream)

1.输出流:从内存中写入到持久性数据存储的硬盘中

2.字节输出流:FileOutputStream

3.write() & write(byte[] b)

4.write(byte[] b, int offset, int len):获取读取到的长度,避免最后一次的字节数量

public class FileOutputStreamDemo {

public static void main(String[] args) throws IOException {

// 需求:将数据写入文件中

// 创建存储数据的文件

File f = new File("e:\\file.txt");

// 创建一个字节输出流

// 文件存在,覆盖;不存在,自动创建

FileOutputStream fos = new FileOutputStream(f);

// 调用父类的write方法

byte[] data = "abcde".getBytes();

fos.write(data);

fos.close();

// 文件的追加和换行

FileOutputStream fos1 = new FileOutputStream(f, true);

String str = "\r\n" + "itcast";

fos1.write(str.getBytes());

fos1.close();

}

}

四、文件的复制以及加密

public class EncryptionFileTest {

public static void main(String[] args) throws IOException {

// 判断是否有该文件

// 读取该文件内容

// 将内容写入另一个文件中

// 关闭文件流

File file = new File("e:/file.txt");

if(file.exists()){

// 读操作/InputStream

InputStream fis = new FileInputStream(file);

// 写操作

OutputStream fos = new FileOutputStream("e:/file-加密.txt");

// 一般使用64k的容器(数组)来存放(搬运)

byte[] buf = new byte[1024 * 8 * 8];

int len;

while ((len = fis.read(buf)) != -1) {

// 加密:异或 -> 一个数异或另一个数两次,得到它本身

for (int i = 0; i < buf.length; i++) {

buf[i] ^= 123456;

}

// 可能会破坏文件结构;最后一次“搬运”中,字节数组不够,自动补0

// fos.write(buf);

fos.write(buf, 0, len);

}

// 原文件加密完进行删除

file.deleteOnExit();

fis.close();

fos.close();

}else{

System.err.println("亲,您还没创建该文件~");

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值