0

我正在尝试接收客户端使用 DataInputStream 发送的文件并将其写入文件。

(客户端使用 DataInputStream write(byte[], len, off) 方法发送文件)

这是我正在尝试做的事情,但它没有收到完整的数据。

InputStream in = s.getInputStream(); //s is Socket that is connected.
BufferedInputStream bis = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bis);

FileOutputStream fos = new FileOutputStream(directory+"/"+filename);

byte b = din.readByte();
while(b != -1){
fos.write(b);
b = din.readByte();
}

我知道上面的实现可能并不优雅。

但我对java真的很陌生,所以请不要对我说不好的风格

(如果你知道的话,我真的很感激你推荐更好的)

结果文件只有 4KB 而它应该是 401KB

我应该如何修复此代码,以便我的代码可以正常工作?

非常感谢您。

4

1 回答 1

2

您正在读取一个字节,并且 -1(转换为一个字节)是一个有效的字节值。您不想在 -1 上停止,而是应该捕获 EOFException。

您在使用标准 InputStream.read() 方法之一(返回int,而不是byte)时测试 -1。

于 2011-10-05T02:54:58.730 回答