通过Java中的套接字传输文件 [英] transferring file through socket in Java

查看:70
本文介绍了通过Java中的套接字传输文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Java中的套接字传输文件.实际上我已经能够传输..但是发生了一个问题..问题是发送的文件尺寸缩小了.例如,我传输了300mb文件,客户端只会收到299mb....我在想可能是问题所在..

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..

服务器端

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();

客户端

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();

推荐答案

在Java中复制流的规范方法如下:

The canonical way to copy a stream in Java is as follows:

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.

如果要发送多个文件,则需要先通过DataOutputStream.writeLong();发送长度.通过反函数在另一端读取它;并调整读取结束时的循环条件,使其在读取完同样多的字节后终止.看起来并不那么简单;留给读者练习.

If you are sending more than one file you need to send the length first, via 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.

这篇关于通过Java中的套接字传输文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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