I'm trying to write two methods for send and receive file with java socket in a client-server application and I have some doubts:
I use FileInputStream
and FileOutputStream
. Are BufferedInputStream
and BufferedOutputStream
better?
static protected long send_file(File file, DataOutputStream output) throws IOException, FileNotFoundException, SecurityException
{
byte[] buffer = new byte[1024];
long count = 0;
int nread = 0;
FileInputStream file_input = new FileInputStream(file);
output.writeLong(file.length());
while((nread = file_input.read(buffer)) != -1)
{
output.writeInt(nread);
output.write(buffer, 0, nread);
count += nread;
}
output.flush();
file_input.close();
return count;
}
static protected long receive_file(File file, DataInputStream input) throws IOException, FileNotFoundException, SecurityException, EOFException
{
byte[] buffer = new byte[1024];
long dim_file = 0;
long count = 0;
int nbyte = 0;
int nread = 0;
int n = 0;
FileOutputStream file_output = new FileOutputStream(file);
dim_file = input.readLong();
while(count < dim_file)
{
nbyte = input.readInt();
nread = input.read(buffer, 0, nbyte);
if(nread == -1)
{
file_output.close();
throw new EOFException();
}
while(nread < nbyte)
{
n = input.read(buffer, nread, nbyte-nread);
if(n == -1)
{
file_output.close();
throw new EOFException();
}
nread += n;
}
file_output.write(buffer, 0, nread);
count += nread;
}
file_output.flush();
file_output.close();
return count;
}
I don't understand the necessity of BufferedInputStream
and BufferedOutputStream
:
In the first method, I use a buffer of 1024 byte and first I fill it with FileInputStream.read(byte[] b)
and then send it to socket with DataOutputStream.write(byte[] b, int off, int len)
.
In the second method idem: first I fill the buffer with DataInputStream.read(byte[] b)
and then write to the file with FileOutputStream.write(byte[] b, int off, int len)
.
So why use BufferedInputStream
and BufferedOutputStream
?
In this way, if I understand how they work, I write bytes first in my buffer and then BufferedInputStream
and BufferedOutputStream
copy bytes in their buffer.
If you dont use buffered streams Java IO will make an operating system call each time you write /read a byte whether it is writing / reading to file or socket which is extremely inefficient.