I have been trying to send a big file over a Socket connection, but it runs slowly and I was wondering if this code can be optimized in some way to improve the transfer speed.
This is my code for sending the file:
byte[] buffer = new byte[65536];
int number;
while ((number = fileInputStream.read(buffer)) != -1) {
socketOutputStream.write(buffer, 0, number);
}
socketOutputStream.close();
fileInputStream.close();
This is what I use to receive the file on the other machine:
byte[] buffer = new byte[65536];
InputStream socketStream= clientSocket.getInputStream();
File f=new File("C:\\output.dat");
OutputStream fileStream=new FileOutputStream(f);
while ((number = socketStream.read(buffer)) != -1) {
fileStream.write(buffer,0,number);
}
fileStream.close();
socketStream.close();
I think writing to the fileStream is taking the majority of the time. Could anyone offer any advise for speeding up this code.
There’s nothing obviously wrong with that code, other than the lack of
finallyblocks for theclosestatements.How long does it take for how much data? It’s very unlikely that the
FileOutputStreamis what’s taking the time – it’s much more likely to be the network being slow. You could potentially read from the network and write to the file system in parallel, but that would be a lot of work to get right, and it’s unlikely to give that much benefit, IMO.