Java: reading from a binary file, sending bytes through a socket

It should be easy, but right now I can’t lower my head. I want to send some bytes through a socket, for example

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

This works, but now I do not want to write Byte to Outputstream, but I read from a binary file and then write it. I know (?) I need a FileInputStream to read, I just can't figure out how to build it all.

Can someone help me?

+3
source share
3 answers
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();
}

It would be a naive approach without correctly handling exceptions - in the real world you would need to close threads if an error occurs.

, , . , FileChannel transferTo (...), .

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

        String fileName = "....";

FileInputStream fileName

    FileInputStream fis = new FileInputStream(fileName);

FileInputStream File

        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

read the byte from the input and write the same byte to the output

or with a byte buffer:

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

note that you do not need to use a DataStream for this

0
source

All Articles