1

我在将文件从服务器传输到客户端时遇到问题。传输完成后,文件已创建,但为空。请注意,当我将它从客户端发送到服务器时,它可以工作。有时我也会在 long fileLength = dis.readLong() 和 String fileName = dis.readUTF() 处得到 EOF 异常。

客户:

private void sendFile(String path) throws IOException {
    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
    DataOutputStream dos = new DataOutputStream(bos);

    File file = new File(path);

    long length = file.length();
    dos.writeLong(length);

    String name = file.getName();
    dos.writeUTF(name);

    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);

    int theByte = 0;
    while((theByte = bis.read()) != -1) 
        bos.write(theByte);

    dos.close();
    bis.close();   

    displayMessage(MESSAGE_SENT);
}

private void getFile() throws IOException {     
    BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
    DataInputStream dis = new DataInputStream(bis);

        long fileLength = dis.readLong();
    String fileName = dis.readUTF();

    File file = new File(System.getProperty("user.dir") + "/" + fileName);

    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    int theByte = 0;
    while((theByte = bis.read()) != -1) 
        bos.write(theByte);

    bos.close();
    dis.close();
    displayMessage(MESSAGE_DOWNLOADED);
}

服务器:

private void sendFile(String path) throws IOException {     
    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
    DataOutputStream dos = new DataOutputStream(bos);

    File file = new File(path);

    long length = file.length();
    dos.writeLong(length);

    String name = file.getName();
    dos.writeUTF(name);

    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);

    int theByte = 0;
    while((theByte = bis.read()) != -1) 
        bos.write(theByte);

    dos.close();
    bis.close();

    displayMessage(MESSAGE_SENT);
}

private void getFile() throws IOException {     
    BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
    DataInputStream dis = new DataInputStream(bis);

    long fileLength = dis.readLong();
    String fileName = dis.readUTF();

    File file = new File(System.getProperty("user.dir") + "/" + fileName);

    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    for(int j = 0; j < fileLength; j++) 
        bos.write(bis.read());

    bos.close();
    dis.close();
    displayMessage(MESSAGE_DOWNLOADED);
}
4

1 回答 1

0

我认为问题在于不刷新您的输出流。像这样:

 int theByte = 0;
 while((theByte = bis.read()) != -1) 
       bos.write(theByte);

    dos.flush();

    dos.close();
    bis.close();
于 2013-10-02T15:03:18.593 回答