使用DataInputStream接收文件信息并写入
我正在尝试接收客户端使用 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
我应该如何修复这个代码,这样我就可以有我的代码工作吗?
非常感谢。
I am trying to receive a file that client sends using DataInputStream and write it into file.
(Client sends the file using DataInputStream write(byte[], len, off) method)
Here's how I am trying to do, but it does not receive full data.
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();
}
I know that the implementation above may not be elegant.
but I am really new to java so please forbear with me about bad style
(I really appreciate if you recommend better one if you know)
the result file is only 4KB whereas it should be 401KB
How should I fix this code so I can have my code working?
THank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在读取一个字节,-1(转换为字节)是一个有效的字节值。您不想在 -1 处停止,而应该捕获 EOFException。
使用标准 InputStream.read() 方法之一(返回
int
,而不是byte
)时测试 -1。you are reading a byte, and -1 (cast to a byte) is a valid byte value. you don't want to stop on -1, but should instead catch EOFException.
you test for -1 when using one of the standard InputStream.read() methods (which return
int
, notbyte
).