用字节流复制文件的几种方式

最近学了IO的一些内容,想把每一种流都弄清楚,就FileInputStream和FileOutputStream为例。编写了5种复制文件的方法。要是我有新的想法我会再补充的。

方法一:

File file = new File("D:\\demo.txt");
		try {
			FileOutputStream out = new FileOutputStream("D:"+File.separator+"me.txt");
			FileInputStream in = new FileInputStream(file);
 
			int len = (int) file.length();//得到文件的长度
			int hasRead = 0;
			int temp = 0;
			while((hasRead=in.read())!=-1){
				out.write(hasRead);
				temp++;
				if(temp==len){//当读取的长度和文件长度相同时停止
					break;
				}
			}
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

方法二:

File file = new File("D:\\demo.txt");
		try {
			FileOutputStream out = new FileOutputStream("D:"+File.separator+"me.txt");
			FileInputStream in = new FileInputStream(file);
 
			int len = (int) file.length();//得到文件的长度
			byte[] b = new byte[len];
			in.read(b, 0, len);
			out.write(b);
			/*
			 * out.flush(); 最好有该方法。
			 * flush all the streams immediately before close them,
			 * otherwise data left in the buffer when the stream is closed may get lost
			 */
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

方法三:

File file = new File("D:\\demo.txt");
		try {
			FileOutputStream out = new FileOutputStream("D:"+File.separator+"me.txt");
			FileInputStream in = new FileInputStream(file);
 
			int len = (int) file.length();//得到文件的长度
			byte[] b = new byte[len];
			for(int i=0; i<b.length; i++){
				b[i] = (byte)in.read();
			}
			out.write(b);
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

方法四:

File file = new File("D:\\demo.txt");
		try {
			FileOutputStream out = new FileOutputStream("D:"+File.separator+"me.txt");
			FileInputStream in = new FileInputStream(file);
 
			int len = (int) file.length();//得到文件的长度
			byte[] b = new byte[len];
			do{
				in.read(b, 0, len);
				out.write(b);
			}while(in.available()>0);
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

方法五:

File f=new File("D:\\demo.txt");
        try {
			FileInputStream input=new FileInputStream(f);
			FileOutputStream output = new FileOutputStream(new File("D:\\me.txt"));
			byte b[]=new byte[input.available()];
			input.read(b, 0,input.available() ); //available() 返回可以无阻塞地读取的字节数
			output.write(b);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值