为什么文件在Java套接字的客户端损坏?

问题描述

| 我编写了一个Java代码,该代码使用using1ѭ和
BufferedInputStream
从服务器向客户端发送
.exe
文件,但是该文件在客户端已损坏。 可能是什么原因?
command1= ServerFrame.msg1+\".exe\";
File p=new File(command1);
FileInputStream f=new FileInputStream(p);
BufferedInputStream bis=new BufferedInputStream(f);
Integer d=bis.available();
int d1=d;
byte b[]=new byte[d];
bis.read(b,d1);
System.out.println(d1);
dos=new DataOutputStream(s.getoutputStream());
bufferedoutputstream bos=new bufferedoutputstream(s.getoutputStream());
dos.writeUTF(d.toString());             // sending length in long
bos.write(b,d1);                      // sending the bytess

bos.flush();
bis.close();  
bos.close();
dos.close();      
    

解决方法

        我想
s
是你的插座。您的代码中几乎没有什么可以做的:
bis.available()
返回不加阻塞的情况下可以读取的字节数,而不是文件的总大小,应使用循环读取文件 您可以在两个不同的缓冲区中使用输出流,并且无需刷新就可以对它们进行写入;另外,为什么还要编写UTF? 这是您打算做的事情:
private void copy(InputStream in,OutputStream out) {
    byte[] buf = new byte[0x1000];
    int r;
    while ((r = in.read(buf)) >= 0) {
        out.write(b,r);
    }
}
InputStream in = new BufferedInputStream(new FileInputStream(path));
OutputStream out = new BufferedOutputStream(s.getOutputStream());
copy(in,out);
in.close();
out.close();
    ,        bis.available()返回可读取的字节,它可能不是完整的内容大小,您必须循环读取直到达到EOF。     ,        如果有人遇到同样的问题,在这种情况下,缓冲区大小是罪魁祸首:
Integer d=bis.available(); 
byte b[]=new byte[d];
尝试使用1024或更小一些:
byte b[]=new byte[1024];
希望这可以帮助..