Java—字节流

一、IO原理

无标题.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):获取读取到的长度,避免最后一次的字节数量<byte[]申请的数量,出现其它没有字符的位置上有0;有可能破坏文件的结构

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("亲,您还没创建该文件~");
		}
		
	}
}
posted @ 2020-11-14 16:39  娜豆  阅读(107)  评论(0编辑  收藏  举报