How to send file to a port?

Guys,Need your help on how to send a file to a port (sample network port)?Thanks,Mercy
[114 byte] By [mespedila] at [2007-11-27 7:48:35]
# 1

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();

}

}

Arash.Shahkara at 2007-7-12 19:29:27 > top of Java-index,Java Essentials,Java Programming...
# 2
Arash.Shahkar , Why byte array declared as 1024?Thanks,Mercy
mespedila at 2007-7-12 19:29:27 > top of Java-index,Java Essentials,Java Programming...
# 3
8192 or more would be a much better choice.And why synchronize on the buffer? Why not just make it local?
ejpa at 2007-7-12 19:29:27 > top of Java-index,Java Essentials,Java Programming...
# 4

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();

}

}

Arash.Shahkara at 2007-7-12 19:29:27 > top of Java-index,Java Essentials,Java Programming...