简体   繁体   English

Java中的客户端服务器文件传输

[英]Client-Server File Transfer in Java

I'm looking for an efficient way to transfer files between client and server processes using TCP in Java. 我正在寻找一种使用Java中的TCP在客户端和服务器进程之间传输文件的有效方法。 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. 我知道我想从fis读取字节,然后将它们写入os ,但是我不确定使用Java中的字节流读取和写入字节的最佳方法。 I'm only familiar with writing/reading text using Writers and Readers. 我只熟悉使用Writer和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) 我应该在其中包装osfis (如果有),以及如何在没有hasNext()方法(或等效方法hasNext()情况下继续读取字节直到文件结束

You could do something like: 您可以执行以下操作:

byte[] contents = new byte[BUFFER_SIZE];
int numBytes =0;
while((numBytes = is.read(contents))>0){
   os.write(contents,0,numBytes);
}  

You could use Apache's IOUtils.copy(in, out) or 您可以使用Apache的IOUtils.copy(in,out)或

import org.apache.commons.fileupload.util.Streams;
...
Streams.copy(in, out, false);

Inspecting the source might prove interesting. 检查源可能很有趣。 ( http://koders.com ?) 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. 有一个带有transferTo方法的java.nio.Channel,社区中的意见不一,对于较小/较大的文件来说更好。

A simple block wise copy between Input/OutputStream would be okay. 在Input / OutputStream之间进行简单的逐块复制就可以了。 You could wrap it in buffered streams. 您可以将其包装在缓冲流中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM