0

我正在尝试构建一个使用 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...");
}

谁能告诉我为什么它陷入无限循环?如果是因为没有使用 available ,请告诉我如何使用它?我实际上用谷歌搜索,但我对用法感到困惑。非常感谢

4

3 回答 3

2

我想你想做while(readByte != -1)。请参阅文档(-1 表示没有更多可阅读的内容)。

回应评论

这对我有用:

FileInputStream in = new FileInputStream(new File("C:\\Users\\Rachel\\Desktop\\Test.txt"));
DataInputStream din = new DataInputStream(new BufferedInputStream(in));
FileOutputStream fos = new FileOutputStream("C:\\Users\\Rachel\\Desktop\\MyOtherFile.txt");

byte b[] = new byte[512]; 
while(din.read(b) != -1){
    fos.write(b);
}

System.out.println("Got out");
于 2011-10-05T03:37:38.643 回答
0

正如 Rachel 指出的那样,DataInputStream 上的read方法返回成功读入的字节数,如果已到达末尾,则返回 -1。循环直到到达终点的惯用方式是while(readByte != -1)1错误地这样做了。如果永远不会读取恰好 1 个字节,那么这将是一个无限循环(readByte一旦到达流的末尾,就永远不会从 -1 更改)。如果碰巧有一个迭代恰好读取了 1 个字节,那么这实际上会提前终止,而不是进入无限循环。

于 2011-10-05T03:44:38.657 回答
0

您的问题已得到解答,但此代码还有另一个问题,已在下面更正。规范的流复制循环如下所示:

while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}
于 2011-10-05T04:02:26.300 回答