我试图通过java中的套接字传输文件...实际上我已经能够转移..但是出现了一个问题..问题是发送的文件是缩小的大小...例如我传输300mb文件,客户将只收到299mb ....我想知道可能是什么问题..
服务器端
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();
答案 0 :(得分:2)
在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);
}
适用于任何长度输入;不会将整个输入加载到内存中;这样做不会增加延迟。
如果您要发送多个文件,则需要先通过DataOutputStream.writeLong()发送长度;通过反函数在另一端读取它;调整读取端的循环条件,在读取完多个字节后终止。不像它看起来那么简单;留给读者练习。