【发布时间】:2013-06-09 15:32:00
【问题描述】:
我正在尝试在客户端-服务器应用程序中编写两种使用 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和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 和BufferedOutputStream?
这样,如果我了解它们的工作原理,我会先在缓冲区中写入字节,然后 BufferedInputStream 和 BufferedOutputStream 在它们的缓冲区中复制字节。
【问题讨论】:
-
必要的,没有。可取的,是的。
标签: java sockets bufferedinputstream bufferedoutputstream