我正在尝试在客户端-服务器应用程序中编写两种使用 java 套接字发送和接收文件的方法,但我有一些疑问:
我使用FileInputStream
和FileOutputStream
。是BufferedInputStream
和BufferedOutputStream
更好?
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;
}
我不明白BufferedInputStream
and的必要性BufferedOutputStream
:
在第一种方法中,我使用了一个 1024 字节的缓冲区,首先我FileInputStream.read(byte[] b)
用DataOutputStream.write(byte[] b, int off, int len)
.
在第二种方法同上:首先我用 填充缓冲区,DataInputStream.read(byte[] b)
然后用FileOutputStream.write(byte[] b, int off, int len)
.
那么为什么要使用BufferedInputStream
andBufferedOutputStream
呢?这样,如果我了解它们的工作原理,我会先在缓冲区中写入字节,然后再BufferedInputStream
在BufferedOutputStream
缓冲区中复制字节。