Reputation: 3
i am trying to transfer file through socket in java..actually i have been able to transfer..but there is one problem occured..the problem is the file sent is shrink in size..for example i transfer 300mb file, the client will receive only 299mb....i was wondering what might be the problem..
Server Side
File myFile = new File (basePath+"\\"+input.readUTF());
byte [] mybytearray = new byte [1024];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
txtArea.append("Sending... \n");
while (true)
{
int i = bis.read(mybytearray, 0, mybytearray.length);
if (i == -1) {
break;
}
output.write(mybytearray, 0, i);
txtArea.append("Sending chunk " + i + "\n");
}
output.flush();
Client Side
output.writeUTF("get");
txtArea.append("Starting to recive file... \n");
long start = System.currentTimeMillis();
byte [] mybytearray = new byte [1024];
txtArea.append("Connecting... \n");
output.writeUTF(remoteSelection);
FileOutputStream fos = new FileOutputStream(basePath+"\\"+remoteSelection);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = input.read(mybytearray, 0, mybytearray.length);
while(bytesRead != -1)
{
bos.write(mybytearray, 0, bytesRead);
txtArea.append("got chunk" + bytesRead +"\n");
bytesRead = input.read(mybytearray, 0, mybytearray.length);
}
bos.flush();
Upvotes: 0
Views: 2279
Reputation: 311028
The canonical way to copy a stream in Java is as follows:
int count;
byte[] buffer = new byte[8192]; // or whatever you like really, not too small
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Works for any length input; does not load the entire input into memory; does not add latency by so doing.
If you are sending more than one file you need to send the length first, via DataOutputStream.writeLong(); read it at the other end via the inverse function; and adjust the loop condition at the reading end to terminate after reading exactly that many bytes. Not quite as simple as it may appear; left as an exercise for the reader.
Upvotes: 3