3

这应该很容易,但我现在无法理解它。我想通过套接字发送一些字节,比如

Socket s = new Socket("localhost", TCP_SERVER_PORT);
DataInputStream is = new DataInputStream(new BufferedInputStream(s.getInputStream()));

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));

for (int j=0; j<40; j++) {
  dos.writeByte(0);
}

那行得通,但是现在我不想将写入字节写入输出流,而是从二进制文件中读取,然后将其写出。我知道(?)我需要一个 FileInputStream 来读取,我只是无法弄清楚构建整个事物的热度。

有人可以帮我吗?

4

3 回答 3

4
public void transfer(final File f, final String host, final int port) throws IOException {
    final Socket socket = new Socket(host, port);
    final BufferedOutputStream outStream = new BufferedOutputStream(socket.getOutputStream());
    final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(f));
    final byte[] buffer = new byte[4096];
    for (int read = inStream.read(buffer); read >= 0; read = inStream.read(buffer))
        outStream.write(buffer, 0, read);
    inStream.close();
    outStream.close();
}

如果没有适当的异常处理,这将是一种天真的方法——在现实世界中,如果发生错误,您必须确保关闭流。

您可能想查看 Channel 类以及流的替代方案。例如,FileChannel 实例提供了可能更有效的 transferTo(...) 方法。

于 2012-05-16T12:33:47.377 回答
2
        Socket s = new Socket("localhost", TCP_SERVER_PORT);

        String fileName = "....";

使用文件名创建 FileInputStream

    FileInputStream fis = new FileInputStream(fileName);

创建一个 FileInputStream 文件对象

        FileInputStream fis = new FileInputStream(new File(fileName));

从文件中读取

    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(
        s.getOutputStream()));

一个字节一个字节地读取它

    int element;
    while((element = fis.read()) !=1)
    {
        dos.write(element);
    }

或从缓冲区中读取

byte[] byteBuffer = new byte[1024]; // buffer

    while(fis.read(byteBuffer)!= -1)
    {
        dos.write(byteBuffer);
    }

    dos.close();
    fis.close();
于 2012-05-16T12:41:03.333 回答
0

从输入读取一个字节并将相同的字节写入输出

或者像这样使用字节缓冲区:

inputStream fis=new fileInputStream(file);
byte[] buff = new byte[1024];
int read;
while((read=fis.read(buff))>=0){
    dos.write(buff,0,read);
}

请注意,您不需要为此使用 DataStreams

于 2012-05-16T12:30:02.123 回答