Rohit Malish
Rohit Malish

Reputation: 3229

Sending file in chunks in Java

I got this client application that sends my file fully to server. But I want it to send file in chunks. Here is my client code:

byte[] fileLength = new byte[(int) file.length()];  

        FileInputStream fis = new FileInputStream(file);  
        BufferedInputStream bis = new BufferedInputStream(fis);

        DataInputStream dis = new DataInputStream(bis);     
        dis.readFully(fileLength, 0, fileLength.length);  

        OutputStream os = socket.getOutputStream();  

        //Sending size of file.
        DataOutputStream dos = new DataOutputStream(os);   
        dos.writeLong(fileLength.length);
        dos.write(fileLength, 0, fileLength.length);     
        dos.flush();  

        socket.close();  

So how can I make client send my file in chunks? Thanks in advance.

Upvotes: 0

Views: 7897

Answers (1)

yohlulz
yohlulz

Reputation: 133

Try to send the file from client in parts, something like

int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}

and reassemble it on the server.

Apache Commons supports streaming, so it may help.

Upvotes: 3

Related Questions