字节流运用1.字节流输入,一次读取一个2.字节流输入,一次读取多个3.字节流实现文件复制:方法一4.字节流实现文件复制:方法二

这篇博客详细介绍了Java中字节流的使用,包括如何一次读取一个字符和多个字符,以及两种不同的文件复制方法。通过 FileInputStream 和 FileOutputStream 进行数据的读写,并演示了如何利用缓冲区提升效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字节流输入,一次读取一个

        File file = new File("E://Test//book.txt");
		//字节流输入
		//一次读取一个
		FileInputStream in = new FileInputStream(file);
		int i = 0;
		while ((i=in.read())!=-1) {
			System.out.print((char)i);
		}
		in.close();

字节流输入,一次读取多个

		File file = new File("E://Test//book.txt");
		//字节流输入
		//一次传多个
		FileInputStream in = new FileInputStream(file);
		
		byte[] buf = new byte[8];
		
		int i = 0;
		
		while ((i=in.read(buf))!=-1) {
			for (int j = 0; j < buf.length; j++) {
				if (buf[j] == 0) {
					break;
				}
				System.out.print((char)buf[j]);
			}
		}
		in.close();

字节流实现文件复制:方法一

		File file = new File("E:\\Test\\book.txt");//调用文件E盘文件
		//读取数据或者写入数据需要运用IO流
		//I:InputStream(输出)   
		FileInputStream in = new FileInputStream(file);
		File filee = new File("F:\\abc\\hello.txt");//调用F盘文件
		//O:OutputStream(输入)
		FileOutputStream out = new FileOutputStream(filee);
		
		int i = 0;//定义i接收read返回的值
		filee.delete();//如果有原文件先删除
		filee.createNewFile();//如果没有新文件则添加
		
		while ((i=in.read())!=-1) {
			out.write(i);
		}

字节流实现文件复制:方法二

		FileInputStream fis=new FileInputStream("E:\\Test\\book.txt");
		  
		FileOutputStream fiss = new FileOutputStream("F:\\abc\\hello.txt");
		  
		byte[] buf = new byte[64];
		while(fis.read(buf)!=-1){
		    System.out.println("---");
		}
		 
		fiss.write(buf);
		fiss.close();

希望能帮到你

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值