java - 使用 datainputstream 和 bufferedinputstream 接收文件时陷入无限循环

标签 java network-programming bufferedinputstream datainputstream

我正在尝试构建一个使用 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/

相关文章:

security - 通过不安全的网络轻松安全地连接(两个端点都完全受控)

java - 如何让我的 java 聊天客户端和服务器从文本字段交换消息

java - 在Java中播放时将mp3文件写入磁盘

java - BufferedStream 链接 Scala(或 Java)

java - 配置 Spring 以设置系统属性 'before' 初始化一个 bean

java - 为什么在同一实体上调用 getOne() 后 "findById()"返回代理?

java - 如何JBOSS部署ESAPI属性文件目录配置

java - 为什么Java中的文件名与公共(public)类名相同?

c - struct hostent 代表什么?

android - 从网络下载图片时如何处理url中的空白区域?