Java: read from binary file, send bytes over socket

假如想象 提交于 2019-12-04 16:24:44
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();
}

This would be the naive approach without proper exception handling - in a real-world setting you'd have to make sure to close the streams if an error occurs.

You might want to check out the Channel classes as well as an alternative to streams. FileChannel instances, for example, provide the transferTo(...) method that may be a lot more efficient.

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

        String fileName = "....";

create a FileInputStream using a fileName

    FileInputStream fis = new FileInputStream(fileName);

create a FileInputStream File Object

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

to read from the file

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

reading from it byte after byte

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

or reading from it buffer wise

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

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

    dos.close();
    fis.close();

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

or with a byte buffer it like this:

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 don't need to use the DataStreams for this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!