简单文件Copy(Java IO 1-1)

Java IO 学习 第一轮 第一个程序

利用 FileInputStream 和 FileOutputStream 可以做一个简单的文件拷贝功能。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class SimpleFileCpy{
	public static void main(String[] args) throws IOException{
		FileInputStream fis = new FileInputStream("D:/kcdown/flashplayer_22.0.0.192.exe");
		FileOutputStream fopt = new FileOutputStream("D:/kcdown/cpy_flsplyr.exe");
		byte[] buff = new byte[512];
		while(fis.read(buff)!=-1){
			fopt.write(buff);
		}
	}
}

运行程序,可以看到在相应目录下生成了拷贝文件。

通过window系统显示大小为 19036KB,二者一样。


而通过文件属性查看却如下:

  

二者存在300多个字节大小的差异。原因在于使用512字节作为缓存区这里。

FileInputStream 从流中按照512byte为单位读取数据,当最终一组数据不足512时,就会填充为0(空)。

解决此问题,需要引入一个int变量 tureSize,代码如下:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class SimpleFileCpy{
	public static void main(String[] args) throws IOException{
		FileInputStream fis = new FileInputStream("D:/kcdown/flashplayer_22.0.0.192.exe");
		FileOutputStream fopt = new FileOutputStream("D:/kcdown/cpy_flsplyr.exe");
		byte[] buff = new byte[512];
		int trueSize = 0;
		while((trueSize=fis.read(buff))!=-1){
			fopt.write(buff,0,trueSize);
		}
	}
}

通过MD5工具,可以看到此次拷贝生成的文件和源文件是完全相同的。



代码中使用到的API:

【API】java.io.FileInputStream

 public int read(byte[] b ) throws IOException 

 参数:b -  the buffer into which the data is read.

 返回:the total number of bytes read into the buffer,or -1 if there is on more data because the end of the file has been reached.

【API】java.io.FileOutputStream

 public void write(byte[] b, int off, int len) throws IOException

 参数:b - the data.

     off - the start offset in the data.

     len - the number of bytes to write.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值