用字节流读写文件

一:IO流分类

1)按流向分:输入流和输出流

2)按数据类型:字节流:可以是一切文件,如纯文本、图片、音乐、视频等

  字符流:只能是纯文本文件

3)按功能分:节点:包裹源头

      处理:增强功能,提供性能

二:字节流(重点)、字符流与文件

1).字节流:输入流:InputStream read(byte[] b) read(byte[] b, int off, int len) close()

如果是文件操作实现类就是FileInputStream,其他操作换用其他实现类就是了。

         输出流:OutputStream write(byte[] b) write(byte[] b, int off, int len) close() flush()

如果是文件操作实现类就是FileOutputStream,其他操作换用其他实现类就是了。

2)字符流:输入流:Reader read(char[] cbuf) read(char[] cbuf, int off, int len) close()

如果是文件操作实现类就是FileReader,其他操作换用其他实现类就是了。

    输出流:Writer write(char[] cbuf) write(char[] cbuf, int off, int len) close() flush()

如果是文件操作实现类就是FileWriter,其他操作换用其他实现类就是了。

三:操作流程:

1)建立联系

2)选择流

3)操作

4)释放资源  


四:读取文件内容:

public static void main(String[] args) {

		// 1.建立联系
		File src = new File("F:/1.txt");
		// 2.选择流
		FileInputStream input = null;// 提升作用域
		try {
			// 3.操作
			input = new FileInputStream(src);
			byte[] data = new byte[100];// 建立缓冲数组,数组长度可变
			int len = 0;// 读出的实际长度
			while ((len = input.read(data)) != -1) {// 不断读取文件内容
				String info = new String(data, 0, len);// 字节数组转换成字符串
				System.out.println(info);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件不存在");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("读取文件失败");
		} finally {
			// 4.释放资源
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
					System.out.println("关闭输入流失败");
				}
			}
		}
	}

五:往文件中写入内容:

public static void main(String[] args) {
		// 1.建立联系
		File src = new File("F:/1.txt");
		// 2.选择流
		FileOutputStream out = null;// 提升作用域
		try {
			out = new FileOutputStream(src, true);// 为true时表示衔接到文件中,为false或者没有时表示覆盖源文件内容
			// 3.操作
			String str = "I must study hard\r\n";// \r\n相当于Enter键-->换行符
			byte[] data = str.getBytes();// 将字符串转换成字节数组
			out.write(data);
			out.flush();// 强制冲刷出去
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件未找到");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件写入异常");
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					System.out.println("文件输出流关闭失败");
				}
			}
		}
	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值