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);
}
}
}
代码中使用到的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.