Java文件的字节输入流与输出流

java文件的字节输入流与输出流

输入和输出相对与程序而言简单的理解就是:将硬盘已有的数据读取到内存中的是输入流,将内存中的数据存储到硬盘中的就是输出流。
字节流:每次操作对对象单位是字节的输入或者输出,最常用的FileInputStream和FileOutputStream两个字节流的子类,其中FileInputStream是输入流,FileOutputStream是输出流
字节的输入流 FileInputStream

下面展示一些 内联代码片

// 给了一个[1024*1]的字节流
// byte[] arr = new byte[1024 * 1];
//这样可以加大流的输入,不用一个一个的字节输入加快输入速率
public static void main(String[] args) {
		// 创建输入流FileInputStream
		FileInputStream fileInput = null;
		try {
			// 创建文件地址
			fileInput = new FileInputStream("E:\\ccw.txt");
			// 给定一个字节大小
			// 每一次读取的时候就可以按照这个字节流输入
			byte[] arr = new byte[1024 * 1];// 给了一个[1024*1]的字节流
			int len = 0;
			while ((len = fileInput.read(arr)) != -1) {
				String str = new String(arr, 0, len);
				System.out.println(str);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 判断文件是否为空不为空关闭输入流
			if (fileInput != null) {
				try {
					fileInput.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

在这里插入图片描述

字节的输出流 FileOutputStream

下面展示一些 内联代码片

public static void main(String[] args) {
		// 先创建一个文件在指定的磁盘下
		// 在E盘下创建一个名为csdn.txt的文本文档的标准文件夹
		String path = "E:" + File.separator + "csdn.txt";
		File file = new File(path);
		FileOutputStream fileOutput = null;
		try {
			// 判断文件是否创建成功
			boolean createNewFile = file.createNewFile();
			System.out.println(createNewFile);
			fileOutput = new FileOutputStream(file);
			// 将字节输出到指定的文件
			String str = "你身处年轻,辜负年轻,也快也将不再年轻!";
			// 将String型的字符串转换为字节数组
			byte[] arr = str.getBytes();
			// 利用write()方法实现输出流
			fileOutput.write(arr);
			// 输出后刷新文件
			fileOutput.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fileOutput != null) {
				try {
					fileOutput.flush();// 刷新文件
					fileOutput.close();// 关闭输出流
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

在这里插入图片描述

在每次完成字节的输入流和输出流是记得关闭流(close()方法)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值