Richard Stokes
Richard Stokes

Reputation: 3552

Client-Server File Transfer in Java

I'm looking for an efficient way to transfer files between client and server processes using TCP in Java. My server code looks something like this:

socket = serverSocket.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();

FileInputStream fis = new FileInputStream(new File(filename));

I'm just unsure of how to proceed. I know I want to read bytes from fis and then write them to os, but I'm unsure about the best way to read and write bytes using byte streams in Java. I'm only familiar with writing/reading text using Writers and Readers. Can anyone tell me the appropriate way to do this? What should I wrap os and fis in (if anything) and how do I keep reading bytes until the end of file without a hasNext() method (or equivalent)

Upvotes: 2

Views: 3430

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

You could use Apache's IOUtils.copy(in, out) or

import org.apache.commons.fileupload.util.Streams;
...
Streams.copy(in, out, false);

Inspecting the source might prove interesting. ( http://koders.com ?)

There is the java.nio.Channel with a transferTo method, with mixed opinions in the community wether better for smaller/larger files.

A simple block wise copy between Input/OutputStream would be okay. You could wrap it in buffered streams.

Upvotes: 2

Chris
Chris

Reputation: 23171

You could do something like:

byte[] contents = new byte[BUFFER_SIZE];
int numBytes =0;
while((numBytes = is.read(contents))>0){
   os.write(contents,0,numBytes);
}  

Upvotes: 3

Related Questions