我正在尝试构建一个使用 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...");
}
谁能告诉我为什么会陷入无限循环?如果是因为没有使用可用的 ,请告诉我如何使用它?我实际上用谷歌搜索过,但我对用法感到困惑。非常感谢
最佳答案
我认为你想做while(readByte != -1)
。请参阅documentation (-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");
关于java - 使用 datainputstream 和 bufferedinputstream 接收文件时陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7656340/