【问题标题】:Send file to server java error将文件发送到服务器java错误
【发布时间】:2013-07-11 23:45:18
【问题描述】:

我有一个通过服务器套接字将文件发送到服务器的代码。我的问题是,对于某些文件,代码可以完美运行,但由于某些其他文件的未知原因,它会丢失最后一个块,因此文件已损坏。

我将不胜感激任何人的帮助。谢谢。

客户端代码。

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

以及刷新和关闭流的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();            
    }
}

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

解决了。我只是把输出冲洗到循环中,它工作得很好。

非常感谢我的朋友们。

【问题讨论】:

  • 在服务器端你没有关闭流

标签: java file sockets send


【解决方案1】:

关闭 fileOut BufferedOutputStream。关闭它,它会将缓冲区刷新到磁盘并关闭流。

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      • 2021-05-15
      • 2018-06-18
      相关资源
      最近更新 更多