在写文件的时候,调用write方法,有时候我们会像这样直接调用write方法.
bos.write(buffer);
同样我们看看底层:
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
如果我们的缓冲区设置为了8192,但是实际的文件比如只有'123'3个字符.
那么我们最后写出的文件就会变成这样:
因为我们读的是b.length,所以最后写文件的时候,虽然后面没有东西输入,但是文件还是会把null null null输出出来.
因此以后我们的工作要养成良好习惯,文件输出的代码应该这么写:
byte[] buffer=new byte[8192];
while((c = bis.read(buffer))!=-1){
bos.write(buffer,0,c);
}
bis.close();
bos.close();
这个c就代表你读到数组里面的长度是多少,不会多读,就不会出现null的情况了。
关于flush
很多的代码示例里面会加上
out.flush();
但其实我们看看源码:
public synchronized void write(byte b[], int off, int len) throws IOException {
if (len >= buf.length) {
/* If the request length exceeds the size of the output buffer,
flush the output buffer and then write the data directly.
In this way buffered streams will cascade harmlessly. */
flushBuffer();
out.write(b, off, len);
return;
}
if (len > buf.length - count) {
flushBuffer();
}
System.arraycopy(b, off, buf, count, len);
count += len;
}
当你使用
write(byte b[], int off, int len)
这个方法的时候,源码已经帮你判断了,不需要自己flush
再看close()方法:
public void close() throws IOException {
try {
flush();
} catch (IOException ignored) {
}
out.close();
}
最后close的时候,源码内部也进行了flush().