使用 datainputstream 和 bufferedinputstream 接收文件时陷入无限循环
我正在尝试构建一个使用 DataInputStream 和 BufferedInputStream 从客户端接收文件的服务器程序。
这是我的代码,它陷入无限循环,我认为这是因为没有使用 available() 但我不太确定。
DataInputStream din = new DataInputStream(new BufferedInputStream(s.getInputStream()));
//s is socket that connects fine
fos = new FileOutputStream(directory+"/"+filename);
byte b[] = new byte[512];
int readByte = din.read(b);
while(readByte != 1){
fos.write(b);
readByte = din.read(b);
//System.out.println("infinite loop...");
}
谁能告诉我为什么会陷入无限循环?如果是因为没有使用可用的 ,请告诉我如何使用它?我实际上用谷歌搜索过,但我对用法感到困惑。非常感谢
I am trying to build a server program that receives file from client using DataInputStream and BufferedInputStream.
Here's my code and it falls into infinite loop, I think it's because of not using available() but I am not really sure.
DataInputStream din = new DataInputStream(new BufferedInputStream(s.getInputStream()));
//s is socket that connects fine
fos = new FileOutputStream(directory+"/"+filename);
byte b[] = new byte[512];
int readByte = din.read(b);
while(readByte != 1){
fos.write(b);
readByte = din.read(b);
//System.out.println("infinite loop...");
}
Can anyone tell me why it falls into infinite loop? if it is because of not using available
, would you please tell me how to use it? I actually googled, but I was confused with the usage. Thank you very much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你想做
while(readByte != -1)
。请参阅 文档(-1表示没有什么可读的)。回复评论
这对我有用:
I think you want to do
while(readByte != -1)
. See the documentation (-1 means there is nothing more to read).Response to Comment
This works for me:
正如 Rachel 指出的那样,
read
方法 返回成功读入的字节数,如果已到达末尾则返回 -1。循环直到到达末尾的惯用方法是while(readByte != -1)
,而您错误地使用了1
。如果从来没有读取过 1 个字节,那么这将是一个无限循环(一旦到达流的末尾,readByte
就永远不会从 -1 改变)。如果偶然有一次迭代恰好读取了 1 个字节,则实际上会提前终止,而不是进入无限循环。As Rachel pointed out, the
read
method on DataInputStream returns the number of bytes successfully read in, or -1 if the end has been reached. The idiomatic way to loop until the end has been reached iswhile(readByte != -1)
whereas you had1
by mistake. If it is never the case that exactly 1 byte is read then this will be an infinite loop (readByte
will never change from -1 once the end of the stream has been reached). If by chance there is an iteration where exactly 1 byte is read, this would have actually terminated early instead of going into an infinite loop.您的问题已得到解答,但此代码还有另一个问题,已在下面更正。规范的流复制循环如下所示:
Your question has already been answered but this code has another problem which is corrected below. The canonical stream copy loop looks like this: