Java 中的客户端-服务器文件传输
我正在寻找一种在 Java 中使用 TCP 在客户端和服务器进程之间传输文件的有效方法。我的服务器代码看起来像这样:
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File(filename));
我只是不确定如何继续。我知道我想从 fis 读取字节,然后将它们写入 os,但我不确定在 Java 中使用字节流读写字节的最佳方法。我只熟悉使用作家和读者编写/阅读文本。谁能告诉我执行此操作的适当方法?我应该将 os
和 fis
包装在什么(如果有的话)中,以及如何在没有 hasNext()
的情况下继续读取字节直到文件末尾方法(或等效方法)
I'm looking for an efficient way to transfer files between client and server processes using TCP in Java. My server code looks something like this:
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File(filename));
I'm just unsure of how to proceed. I know I want to read bytes from fis
and then write them to os
, but I'm unsure about the best way to read and write bytes using byte streams in Java. I'm only familiar with writing/reading text using Writers and Readers. Can anyone tell me the appropriate way to do this? What should I wrap os
and fis
in (if anything) and how do I keep reading bytes until the end of file without a hasNext()
method (or equivalent)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做:
You could do something like:
您可以使用 Apache 的 IOUtils.copy(in, out) 或
检查源代码可能会很有趣。 (http://koders.com?)
有一个带有transferTo方法的java.nio.Channel,在社区是否更适合较小/较大的文件。
输入/输出流之间的简单块复制就可以了。您可以将其包装在缓冲流中。
You could use Apache's IOUtils.copy(in, out) or
Inspecting the source might prove interesting. ( http://koders.com ?)
There is the java.nio.Channel with a transferTo method, with mixed opinions in the community wether better for smaller/larger files.
A simple block wise copy between Input/OutputStream would be okay. You could wrap it in buffered streams.