超牛牪犇Java之IO流(前篇)

 流(字节流 以字节为单位 进行数据的传输)

 以参照物来衡量 是输出还是输入

 流的参照物(程序)

  

 输出流

 程序 --> 文件 (写文件使用输出流)

 OutputStream 字节输出流

 

 输入流

 文件 --> 程序 (读取文件使用输入流)

 InputStream  字节输入流

 以上两个类是 所有字节流的父类

 

 写文件步骤

 1.创建要绑定的文件

 2.创建输出流 绑定文件

 3.写文件

 4.关闭流资源

//创建file(给输出流绑定一个输出文件)
//给出的路径可以没有该文件(系统会帮你创建出来)
File file = new File("/Users/lanou/Desktop/test/hello.txt");
//创建文件 字节输出流
FileOutputStream fos = new FileOutputStream(file);
//写文件
//注意:流这块 全是抛的IOException
//传入int值的方法 是按ASCII码输入
fos.write(49);
fos.write(45);
		
//创建一个字节数组
byte[] b = {66,67,68,69};
fos.write(b);
//直接写字符串
//字符串转字节数组 getBytes
//字节数组转字符串 字符串的构造方法
fos.write("wanglong".getBytes());
		
fos.write(b, 1, 2);
//关闭资源
fos.close();

IO流中异常的处理:

//异常处理
File file = new File("/Users/lanou/Desktop/test/hello.txt");
//创建一个空的引用
FileOutputStream fos = null;
try {
	fos = new FileOutputStream(file);
	fos.write("haha".getBytes());
} catch (FileNotFoundException e) {
	//文件找不到 再向下操作无意义
	//停止程序 让程序员修改代码
	//抛个运行时异常 提示信息 和 停止程序
	throw new RuntimeException("文件找不到");			
} catch (IOException e) {
	//写入失败
	throw new RuntimeException("写入是啊比");
}
//关闭资源 一定要确保可以关闭 关闭的代码可以执行
finally {
	//fos创建成功的情况下 才关闭
	if (fos != null) {
		try {
			fos.close();
		} catch (IOException e) {
			throw new RuntimeException("关闭失败");
		}
	}
}

字节输入流:

InputStream

系统读取文件

private static void fun2(FileInputStream fis) throws IOException {
	//循环读取(一次只能读一个字节)
	int num = 0;
	while ((num = fis.read()) != -1) {
		System.out.println((char)num);
	}
	fis.close();
}

一次读取多个:

private static void fun3(FileInputStream fis) throws IOException {
	//一次多读取几个字节
	//一次读两个字节
	//创建一个空的字节数组 长度2
	//利用空的字节数组 作为缓冲区
	//把文件中字节 读进这个数组中
	//一次读俩提高效率
	byte[] b = new byte[2];//一般一次1kb 即1024
	int len = fis.read(b);
	System.out.println(Arrays.toString(b));
	System.out.println(len);
	//返回的是读取的有效位数
	len = fis.read(b);
	System.out.println(Arrays.toString(b));
	System.out.println(len);
	len = fis.read(b);
	System.out.println(Arrays.toString(b));
	System.out.println(len);
	len = fis.read(b);
	System.out.println(Arrays.toString(b));
	System.out.println(len);//-1  读取完毕
	//关闭资源
	fis.close();
}

直接用循环写:

File file = new File("/Users/lanou/Desktop/test/hello.txt");
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[2];
int num = 0;
while ((num = fis.read(b)) != -1) {
	//直接使用string的构造方法  将字节数组转化成字符串
	System.out.print(new String(b, 0, num));
}
//关闭资源
fis.close();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值