我需要做的是使用 DataStreams 发送多个文件。我通过发送文件名,然后发送文件字节来完成此操作。不过,我需要发送数量不确定的文件。这是DataOutputStream
代码。
out.writeUTF(path);
out.write(Files.readAllBytes(file.toPath()));
它对每个需要发送的文件执行此操作。但我不知道如何用DataInputStream
正确读取它。这就是我到目前为止所拥有的。
while (in.available() != 0) {
String path = in.readUTF();
byte bytes = in.readByte();
}
显然这是行不通的,因为它只读取一个字节。但我不知道如何让它读取所有字节。由于有多个文件正在发送,我认为,当读取所有文件的末尾时,available() 只会等于 0。非常感谢任何帮助。
我完全忘记提及,我希望能够在不耗尽内存的情况下发送大文件,但我认为这行不通。我想我需要使用缓冲区,但我不知道哪个类支持文件。
最佳答案
每当您发送可变长度消息时,您都需要某种方法来标记每个方法的开始和结束。
List<File> files = someListOfFilesYouWantToSend;
out.writeInt(files.size());
for(File file : files){
out.writeUTF(path);
out.writeLong(file.getTotalSpace());
out.write(Files.readAllBytes(file.toPath()));
}
然后要阅读它,你会做这样的事情
int filesToRead = in.readInt();
for(int i = 0; i < filesToRead; i++){
String path = in.readUTF();
long bytesToRead = in.readLong();
FileOutputSteam fos = new FileOutputStream(path);
byte[] buffer = new byte[1024];
while(bytesToRead > 0){
bytesRead = in.read(buffer,0,bytesToRead > buffer.length ? buffer.length : bytesToRead);
bytesToRead -= bytesRead;
fos.write(buffer);
}
}
关于java - 从 DataInputStream 读取几个 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10216590/