Java Graphics How to - Transfer Image with Socket stream








Question

We would like to know how to transfer Image with Socket stream.

Answer

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.Socket;
/* w w  w . j av  a2s  .  co  m*/
public class Main {
  public static void main(String[] args) throws Exception {
    Socket socket = new Socket("localhost", 8000);
    File file = new File("C:/Users/abc/Desktop/image.jpg");
    FileInputStream fileInputStream = new FileInputStream(file);

    byte[] fileBytes = new byte[(int) file.length()];
    OutputStream outputStream = socket.getOutputStream();
    int content;
    while ((content = fileInputStream.read(fileBytes)) != -1) {
      outputStream.write(fileBytes, 0, (int) file.length());
    }

    System.out.println("file size is " + fileBytes.length);
    for (byte a : fileBytes) {
      System.out.println(a);
    }
    socket.close();
    fileInputStream.close();
  }
}