您的位置:首页 > 编程语言 > PHP开发

用OutputStream的wirte(byte[] b)方法写入文件 改变了文件的大小?

2016-06-16 12:24 465 查看
后台做了个apk上传的功能,发现上传上去的文件大小变了。 输出流写出用的就是wirte(byte[] b)方法。然后看了看别人怎么写的,改用write(byte[] b,int off,int len)方法就好了。

好神奇的说。为什么会这样呢?看了下wtite(byte[] b)的源码

/**
* Writes <code>b.length</code> bytes from the specified byte array
* to this output stream. The general contract for <code>write(b)</code>
* is that it should have exactly the same effect as the call
* <code>write(b, 0, b.length)</code>.
*
* @param      b   the data.
* @exception  IOException  if an I/O error occurs.
* @see        java.io.OutputStream#write(byte[], int, int)
*/
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}


原来它是调write(b, 0, b.length);这个方法,假设 定义b数组大小10,我们倒数第二次read()到数组的值是[1,2,3,4,5,6,7,8,9,0],长度10个没问题,然后最后一次read()到数组2个值[8,8],这时b数组的实际值是[8,8,3,4,5,6,7,8,9,0],所以如果用wirte(byte[] b)方法直接把数组写入文件就会有额外的([3,4,5,6,7,8,9])数据了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java