如何使用Java中的套接字将文件名与文件一起发送? [英] How do I send file name with file using sockets in Java?

查看:243
本文介绍了如何使用Java中的套接字将文件名与文件一起发送?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码通过套接字传输文件。如何发送文件名?

I have the following code which transfers file via Sockets. How do I send the file name?

Socket socket = new Socket("localhost", port);//machine name, port number
File file = new File(fileName);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) 
{
    System.out.println("File is too large.");
}
byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());

int count;

while ((count = bis.read(bytes)) > 0) 
{
    out.write(bytes, 0, count);
}

out.flush();
out.close();
fis.close();
bis.close();
socket.close();


推荐答案

您可以为套接字创建自己的协议。如果您只需要文件名和数据,则DataOutputStream.writeUTF最简单:

You can invent your own protocol for your socket. If all you need is a filename and data, DataOutputStream.writeUTF is easiest:

BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
try (DataOutputStream d = new DataOutputStream(out)) {
    d.writeUTF(fileName);
    Files.copy(file.toPath(), d);
}

对等体必须使用相同的协议,当然:

The peer must use the same protocol, of course:

BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
try (DataInputStream d = new DataInputStream(in)) {
    String fileName = d.readUTF();
    Files.copy(d, Paths.get(fileName));
}

这篇关于如何使用Java中的套接字将文件名与文件一起发送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆