I have build a simple application that opens a ServerSocket, and on connection, it connects itself to another server socket on a remote machine. To implement port forwarding
Did 2 reads and one buffer check per loop iteration really sped things up and have you measured that? Looks like a premature optimization to me... From personal experience, simply reading into a small buffer and then writing it to the output works well enough. Like that:
byte[] buf = new byte[1024];
int read = m_is.read(buf);
while(read != -1)
{
m_os.write(buf, 0, read);
m_fileOut.write(buf, 0, read);
read = m_is.read(buf);
}
This is from an old proxy of mine that used InputStream.read() in the first version, then went to available() check + 1024 byte buffer in the second and settled on the code above in the third.
If you really really need performance (or just want to learn), use java.nio or one of the libraries that build on it. Do note that IO performance tends to behave wildly different on different platforms.