为什么我们应该使用OutputStream.write(byte [] b,int off,int len)而不是OutputStream.write(byte [] b)? [英] Why should we use OutputStream.write(byte[] b, int off, int len) instead of OutputStream.write(byte[] b)?

查看:1233
本文介绍了为什么我们应该使用OutputStream.write(byte [] b,int off,int len)而不是OutputStream.write(byte [] b)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,大家.这是一个Java初学者的问题,但我认为它将对许多Java学习者有所帮助.

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);
}

上面的代码是FileSenderClient类的一部分,该类用于使用java.io和java.net.Socket将文件从客户端发送到服务器.

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)

代替

os.write(buffer)

以另一种方式问这个问题:为"OutputStream.write()"方法使用"len"参数有什么意义?

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.

推荐答案

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

因为您只想写入实际读取的数据.考虑输入由 N 个缓冲区加一个字节组成的情况.如果没有len参数,您将写入(N+1)*1024字节而不是N*1024+1字节.还考虑从套接字读取的情况,或者甚至是一般的读取情况:InputStream.read()的实际约定是,它传输至少一个字节,而 not 则填充缓冲区.通常由于某种原因而不能.

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.

不,他们不是.

这篇关于为什么我们应该使用OutputStream.write(byte [] b,int off,int len)而不是OutputStream.write(byte [] b)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆