Java:从二进制文件读取,通过套接字发送字节

时间:2012-05-16 12:23:47

标签: java sockets binary-data

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

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

这样可行,但现在我不想将它写入Outputstream,而是从二进制文件中读取,然后将其写出来。我知道(?)我需要一个FileInputStream来读取,我只是无法弄清楚构建整个事情的热点。

有人能帮助我吗?

3 个答案:

答案 0 :(得分:3)

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类以及stream的替代方法。例如,FileChannel实例提供的transferTo(...)方法可能效率更高。

答案 1 :(得分:2)

        Socket s = new Socket("localhost", TCP_SERVER_PORT);

        String fileName = "....";

使用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();

答案 2 :(得分:0)

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

或使用字节缓冲区,如下所示:

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

请注意,您无需为此

使用DataStream