自己说明:
今天在重新学习FileInputSream/FileOutPutSream 读写图片流的时候,发现FileOutPutSream 有两个写的方法。
好像一般人都会用 write(byte[] b,int off,int len)的方法。于是猜,是不是write(byte[] b) 最后一次不满缓冲区长度会有影响。
程序如下:
public class Copic {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException
{
System.out.println(System.getProperty("user.dir"));
FileInputStream input = new FileInputStream("src\\com20130725\\resouce\\test.bmp");
FileOutputStream outPut = new FileOutputStream("src\\com20130725\\resouce\\picCopy.bmp");
int readpicLength=0;
byte[] bytepic = new byte[1024];
//从输入文件读入 字节流到bytepic input.read(bytepic)
while(-1 !=(readpicLength= input.read(bytepic)))
{
//用这个方法,可能带来一个问题,最后一次可能实际写入会比原来的大(最后一次不满1024个字节的时候)
//outPut.write(bytepic);
//所以还是带上实际的字节数
outPut.write(bytepic,0,readpicLength);
}
System.out.println("COPY pic success!");
outPut.close();
input.close();
}
}
经过测试,发现两个方法都可以使用。于是想差别到底在哪里?
网上搜索了下,发现参考了文章:http://liriguang.iteye.com/blog/620610文章。最后一次写入流中的时候,没有按照实际读出的文件写入,而是读入了1024 缓冲区的整数倍。
再仔细查阅了JAVA的源代码,发现如下:
java源代码:
public void write(byte b[]) throws IOException {
socketWrite(b, 0, b.length);
}
public void write(byte b[], int off, int len) throws IOException {
socketWrite(b, off, len);
}
其中,socketWrite是底层的native的方法。
可以看到,write的两个方法,调用的最后一个参数不一样。在逐个读入的时候,write(byte b[])是读入的缓冲区的整数倍,也就是我们上文的1024;
而write(byte b[], int off, int len)读入的是实际读到的大小。
在没有到达最后一次读入的时候,都是一样的。
最后一次不满1024个字节的时候,就有差别了。
做技术还是要仔细啊!
参考了文章:http://liriguang.iteye.com/blog/620610