0

我正在使用 java 套接字编写客户端/服务器。有我的代码:

服务器:

public void sendFile(File file) {
    BufferedOutputStreambufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
    int count;
    FileInputStream in;
    try {
        in = new FileInputStream(file);
        byte[] mybytearray = new byte[(int) file.length()];
        while ((count = in.read(mybytearray)) > 0) {
            bufferedOutputStream.write(mybytearray, 0, count);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

客户:

public void downloadFile() {
    BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
    byte[] aByte = new byte[8192];
    int count;
    FileOutputStream in;
    try {
        in = new FileOutputStream("C://fis.txt");
        while ((count = bufferedInputStream.read(aByte)) > 0) {
        System.out.println(count); // <- nothing happens
            in.write(aByte, 0, count);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

为什么第二个函数中的 bufferedInputStream 是空的?

4

1 回答 1

3

BufferedOutputStream在缓冲区满之前不会写入数据。您需要冲洗 OutputStream

bufferedOutputStream.flush();
于 2013-04-01T14:58:09.770 回答