Reputation: 1267
What I need to do is send multiple files using DataStreams. I'm doing this by sending the name of the file, and then the file's bytes. I need to send an undetermined number of files though. Here is the DataOutputStream
code.
out.writeUTF(path);
out.write(Files.readAllBytes(file.toPath()));
It does that for each file that needs to be sent. But I don't know how to read it correctly with DataInputStream
. This is what I have so far.
while (in.available() != 0) {
String path = in.readUTF();
byte bytes = in.readByte();
}
Obviously it wouldn't work, since it is only reading one byte. But I don't know how to make it read all of the bytes. Since there are several files being sent, available()
would only equal 0 when the end of all the files are read, I think. Any help is greatly appreciated.
Something I completely forgot to mention, I want to be able to send a large file without running out of memory, and I don't think this would work. I think I would need to use a buffer, but I don't know what class supports that with files.
Upvotes: 1
Views: 2979
Reputation: 5587
Anytime you send variable length messages you need some way to mark the beginning and end of each method.
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()));
}
Then to read it you would do something like this
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);
}
}
Upvotes: 2
Reputation: 4958
That's not the way to do it... Why won't you simply archive all the files you want to send in an archive (like a JAR or ZIP)? On the receiving side you can extract the archive. Java has a built-in JAR implementation (in package java.util.jar) that you can use.
Upvotes: 0