10

我已使用此处的代码通过套接字发送单个文件。但是,我需要能够通过套接字发送多个文件(基本上是目录中的所有文件)并让客户端识别文件之间的分隔方式。坦率地说,我完全不知道该怎么做。任何提示都会有所帮助。

注意 1:我需要一种将文件发送到一个连续流中的方法,客户端可以将其分离为单个文件。它不能依赖于客户的个别请求。

注意 2:要回答一个问题,我很确定我会在评论中看到,不,这不是家庭作业。

编辑有人建议我可以在文件本身之前发送文件的大小。我该怎么做,因为通过套接字发送文件总是在预定的字节数组或单个字节中完成,而不是由返回的 longFile.length()

4

5 回答 5

22

这是一个完整的实现:

发送方:

String directory = ...;
String hostDomain = ...;
int port = ...;

File[] files = new File(directory).listFiles();

Socket socket = new Socket(InetAddress.getByName(hostDomain), port);

BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);

dos.writeInt(files.length);

for(File file : files)
{
    long length = file.length();
    dos.writeLong(length);

    String name = file.getName();
    dos.writeUTF(name);

    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);

    int theByte = 0;
    while((theByte = bis.read()) != -1) bos.write(theByte);

    bis.close();
}

dos.close();

接收方:

String dirPath = ...;

ServerSocket serverSocket = ...;
Socket socket = serverSocket.accept();

BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);

int filesCount = dis.readInt();
File[] files = new File[filesCount];

for(int i = 0; i < filesCount; i++)
{
    long fileLength = dis.readLong();
    String fileName = dis.readUTF();

    files[i] = new File(dirPath + "/" + fileName);

    FileOutputStream fos = new FileOutputStream(files[i]);
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    for(int j = 0; j < fileLength; j++) bos.write(bis.read());

    bos.close();
}

dis.close();

我没有测试它,但我希望它会工作!

于 2012-07-10T19:46:58.607 回答
2

您可以在每个文件之前先发送文件的大小,这样客户端就会知道当前文件何时结束并期待下一个(大小)。这将允许您对所有文件使用一个连续的流。

于 2012-07-10T19:26:31.303 回答
1

一个非常简单的方法是在发送每个文件之前发送文件长度,以便您可以确定文件之间的分隔。

当然,如果接收进程是Java,你可以只发送Objects。

于 2012-07-10T19:27:00.233 回答
0

您可以在客户端压缩文件并将此压缩流发送到服务器。

例如:http ://www.exampledepot.com/egs/java.util.zip/CreateZip.html

和 ...

OutputStream output = connection.getOutputStream();
ZipOutputStream out = new ZipOutputStream(output);
于 2012-07-10T19:20:58.357 回答
0

也许最快的方法是自动将您目录中的文件压缩和解压缩到一个文件中,请参见 java.util.zip 包

于 2012-07-10T19:22:03.490 回答