21-IO流-22-IO流(字节流-练习-复制MP3)

/*
 * 需求:复制一个mp3媒体文件。
 */

package demo;

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

public class CopyMp3Test {

	public static void main(String[] args) throws IOException {

		copy_4();
	}

	public static void copy_4() throws IOException {//读一个字节,写一个字节,速度太慢,所以这种方式千万别用
		
		FileInputStream fis = new FileInputStream("0.mp3");
		FileOutputStream fos = new FileOutputStream("4.mp3");
		
		int ch = 0;
		while((ch = fis.read())!=-1){
			fos.write(ch);
		}
		fis.close();
		fos.close();
	}

	public static void copy_3() throws IOException {//该方法虽然简单,但是有局限性,如果文件过大,会造成内存崩溃
		
		FileInputStream fis = new FileInputStream("0.mp3");
		FileOutputStream fos = new FileOutputStream("3.mp3");
		
		byte[] buf = new byte[fis.available()];
		fis.read(buf);
		fos.write(buf);
		fis.close();
		fos.close();
	}

	public static void copy_2() throws IOException {//利用缓冲区进行复制
		
		FileInputStream fis = new FileInputStream("0.mp3");
		BufferedInputStream bufis = new BufferedInputStream(fis);
		
		FileOutputStream fos = new FileOutputStream("2.mp3");
		BufferedOutputStream bufos = new BufferedOutputStream(fos);
		
		int ch = 0;
		while((ch = bufis.read())!=-1){
			bufos.write(ch);
			//bufos.flush();//用到缓冲区,切记刷新
		}
		
		bufis.close();
		bufos.close();
	}

	public static void copy_1() throws IOException {
		
		FileInputStream fis = new FileInputStream("0.mp3");
		
		FileOutputStream fos = new FileOutputStream("1.mp3");
		
		byte[] buf = new byte[1024];
		
		int len = 0;
		while((len = fis.read(buf))!=-1){//如果这里不指定buf,那么会有危险,因为会一直不断往1.mp3里面写入源中的第一个元素
			fos.write(buf,0,len);
		}
		
		fis.close();
		fos.close();
		
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值