【发布时间】:2013-03-27 00:32:55
【问题描述】:
我有以下通过套接字传输文件的代码。如何发送文件名?
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();
【问题讨论】:
-
如何用文件发送文件名?如果我是正确的使用
File.getName() -
我认为 OP 正在寻找协议定义,以便接收端可以知道将文件存储在哪里。这需要记录结束标记等 - 为什么不使用完善的协议,如 FTP?
-
@RonDahlgren 因为 FTP 有点糟糕,为此目的有点矫枉过正,而且我不确定 Java 对它的支持是否有用?对于从发送者 A 到不一定是文件系统形状的接收者 B 的简单文件上传,HTTP 会更好。
-
有了 TCP 套接字,你基本上可以发送任何东西,它不限于某些类/类型。将每个对象/变量视为字节的集合。
-
不,我正在构建一个 p2p 网络。发送文件时,接收方只需要知道文件名,不需要知道文件存放在哪里。它可以存储在任何地方。