You have to read through a file input stream and send read data through your socket output stream. Assume you have a established Socket (socket), consider the following code:
final int SIZE = 1024;
byte[] buffer = new byte[SIZE];
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream("myfile.ext");
out = socket.getOutputStream();
while (true) {
synchronized (buffer) {
int amountRead = in.read(buffer);
if (amountRead == -1) {
break;
}
out.write(buffer, 0, amountRead);
}
}
} catch(IOException err) {
// Do some error handling here...
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
The declared buffer size was just an example. As ejp said, increasing the buffer size to 8192 bytes or 16384 bytes is better, and improves the performance. But try too keep it balanced, don't make it very large.
To the OP: There's lots of experience behind what ejp says, so when he says something, do it.
The code changes to the following:
final int SIZE = 8192;
byte[] buffer = new byte[SIZE]; // Make this local. You can wrap all this code in a method, for example.
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream("myfile.ext");
out = socket.getOutputStream();
int amountRead;
while ((amountRead=in.read(buffer))!=-1)
out.write(buffer, 0, amountRead);
} catch(IOException err) {
// Do some error handling here...
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}