[英]transferring file through socket in Java
i am trying to transfer file through socket in java..actually i have been able to transfer..but there is one problem occured..the problem is the file sent is shrink in size..for example i transfer 300mb file, the client will receive only 299mb....i was wondering what might be the problem.. 我正在尝试通过java..socket中的套接字传输文件。实际上我已经能够传输..但是发生了一个问题..问题是发送的文件尺寸缩小了。例如,我传输了300mb文件,客户端只会收到299mb ..我在想可能是什么问题..
Server Side 服务器端
File myFile = new File (basePath+"\\"+input.readUTF());
byte [] mybytearray = new byte [1024];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
txtArea.append("Sending... \n");
while (true)
{
int i = bis.read(mybytearray, 0, mybytearray.length);
if (i == -1) {
break;
}
output.write(mybytearray, 0, i);
txtArea.append("Sending chunk " + i + "\n");
}
output.flush();
Client Side 客户端
output.writeUTF("get");
txtArea.append("Starting to recive file... \n");
long start = System.currentTimeMillis();
byte [] mybytearray = new byte [1024];
txtArea.append("Connecting... \n");
output.writeUTF(remoteSelection);
FileOutputStream fos = new FileOutputStream(basePath+"\\"+remoteSelection);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = input.read(mybytearray, 0, mybytearray.length);
while(bytesRead != -1)
{
bos.write(mybytearray, 0, bytesRead);
txtArea.append("got chunk" + bytesRead +"\n");
bytesRead = input.read(mybytearray, 0, mybytearray.length);
}
bos.flush();
The canonical way to copy a stream in Java is as follows: 在Java中复制流的规范方法如下:
int count;
byte[] buffer = new byte[8192]; // or whatever you like really, not too small
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Works for any length input; 适用于任何长度的输入; does not load the entire input into memory; 不会将整个输入加载到内存中; does not add latency by so doing. 这样做不会增加延迟。
If you are sending more than one file you need to send the length first, via DataOutputStream.writeLong(); 如果要发送多个文件,则需要先通过DataOutputStream.writeLong();发送长度。 read it at the other end via the inverse function; 通过反函数在另一端读取它; and adjust the loop condition at the reading end to terminate after reading exactly that many bytes. 并在读取端调整循环条件,使其在读取完那么多字节后终止。 Not quite as simple as it may appear; 看起来并不那么简单; left as an exercise for the reader. 留给读者练习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.