研究字节流之文件的写入与读出的一些方法1

 

 


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class InputStream_and_OutputStream {

	public static void main(String[] args) throws Exception {
		//Writer();
		//读1 一次读一个字节
		Read1();
		//读2   一次读多个字节
		Read2();
		//读3 一次全部读完
		//Read3();
		
		

	}

	private static void Writer() throws IOException {
		FileOutputStream fileOutputStream=new FileOutputStream("Alano001.txt");
		fileOutputStream.write("仰天大笑出门去,我辈岂是蓬蒿人。".getBytes());
		fileOutputStream.close();
	}
	//读1 一次读一个字节
		public static void Read1() throws IOException {
			//1.创建字节输入流并关联文件
			FileInputStream fileInputStream = new FileInputStream("test1.txt");
			//2.读
			int num = 0;
			while ((num = fileInputStream.read()) != -1) {
				System.out.print((char)num);
			}
			//3.关闭资源
			fileInputStream.close();
		}
	//读2   一次读多个字节
	private static void Read2() throws IOException {
		//1.创建字节输入流并关联文件
		FileInputStream fileInputStream=new FileInputStream("Alano001.txt");
		//2.读
		byte[] by=new byte[1024];
	    while ((fileInputStream.read(by))!=-1) {
			System.out.println(new String(by));
		}
	  //3.关闭资源
		fileInputStream.close();
	}
	//读3  一次全部读完
		public static void Read3() throws IOException {
			//1.创建字节输入流并关联文件
			FileInputStream fileInputStream = new FileInputStream("test1.txt");
			//获取文件的字节个数
			//注意:这种方式适合文件的字节数比较小的时候,大概是几kb之内.
			int num1 = fileInputStream.available();
			//2.读
			byte[] by = new byte[num1];
			fileInputStream.read(by);
			System.out.println(new String(by));
			//3.关闭资源
			fileInputStream.close();
		}

	

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值