Why should we use OutputStream.write(byte[] b, int off, int len) instead of OutputStream.write(byte[] b)?

ⅰ亾dé卋堺 提交于 2019-12-11 15:08:25

问题


Sorry, everybody. It's a Java beginner question, but I think it will be helpful for a lot of java learners.

FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();    
byte[] buffer = new byte[1024];
int len;
while((len=fis.read(buffer)) != -1){
    os.write(buffer, 0, len);
}

The code above is part of FileSenderClient class which is for sending files from client to a server using java.io and java.net.Socket.

My question is that: in the above code, why should we use

os.write(buffer, 0, len)

instead of

os.write(buffer)

In another way to ask this question: what is the point of having a "len" parameter for "OutputStream.write()" method?

It seems both codes are working fine.


回答1:


while((len=fis.read(buffer)) != -1){
    os.write(buffer, 0, len);
}

Because you only want to write data that you actually read. Consider the case where the input consists of N buffers plus one byte. Without the len parameter you would write (N+1)*1024 bytes instead of N*1024+1 bytes. Consider also the case of reading from a socket, or indeed the general case of reading: the actual contract of InputStream.read() is that it transfers at least one byte, not that it fills the buffer. Often it can't, for one reason or another.

It seems both codes are working fine.

No they're not.




回答2:


It actually does not work in the same way.

It is very likely you used a very small text file to test. But if you look carefully, you will still find there is a lot of extra spaces in the end of you file you received, and the size of the file you received is larger than the file you send.

The reason is that you have created a byte array in a size of 1024 but you don't have so many data to put (or read()) into that byte array. Therefore, the byte array is full with NULL in the end part. When it comes to writing to file, these NULLs are still written into the file and show as spaces " " in Windows Notepad...

If you use advanced text editors like Notepad++ or Sublime Text to view the file you received, you will see these NULL characters.



来源:https://stackoverflow.com/questions/45452751/why-should-we-use-outputstream-writebyte-b-int-off-int-len-instead-of-outp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!