有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

将文件发送到服务器java错误

我有一个通过服务器socket将文件发送到服务器的代码。我的问题是,对于某些文件,代码工作得很好,但对于某些其他文件,由于未知原因,它会丢失最后一个块,因此文件已损坏

我将感谢任何人的帮助。谢谢

客户端代码

@Override
public void run(){


    for (File file: sendingFiles){

        try{
            socket=new Socket(host, port);
            out=new BufferedOutputStream(socket.getOutputStream());

            fileIn=new FileInputStream(file);

            byte[] buf=new byte[40*1024];

            int readByte;

            while((readByte=fileIn.read(buf, 0, buf.length))>0){                  

                out.write(buf, 0, readByte);                    

            }

            System.out.println("client out of loop");

            fileIn.close();
            in.close();
            out.close();
            socket.close();

            cancel=false;                

        }catch (IOException e){
            e.printStackTrace();
            this.finish();

        }catch (Exception e){
            e.printStackTrace();
            this.finish();
        }
    }

    this.finish();

}

服务器代码:

@Override
public void run(){

    try{
        in=new BufferedInputStream(socket.getInputStream());
        out=new PrintWriter(socket.getOutputStream(), true);

        fileOut=new BufferedOutputStream(new FileOutputStream(receivingFile));

        byte[] buf=new byte[40*1024];

        out.println("continue");

        int readByte=0;
        while ((readByte=in.read(buf, 0, buf.length))>0){

            fileOut.write(buf, 0, readByte);

        }

        this.finish();

    }catch (IOException e){
        this.finish();
    }catch (Exception e){
        this.finish();
    }
}

以及冲洗和关闭水流的完成方法

 private void finish(){

    if (fileOut!=null){
        try{
            fileOut.flush();
            fileOut.close();
        }catch (IOException e){}
    }
    if (socket!=null){
        try{
            socket.close();
        }catch (IOException e){}
    }

    if (in!=null){
        try{
            in.close();
        }catch (IOException e){}
    }

    if (out!=null){            
        out.close();            
    }
}

请帮帮我。我找不到错误在哪里

解决了。我只是把冲水器放进了循环,效果非常好

非常感谢我的朋友们


共 (0) 个答案