Server receiving file:
public class NioServer { private static final int PORT = 1234; private static final String FILE_NAME = "image.jpg"; public static void main(String args[]) throws IOException { try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) { serverSocketChannel.bind(new InetSocketAddress(PORT)); try (SocketChannel socketChannel = serverSocketChannel.accept()) { try (FileChannel fileChannel = FileChannel.open(Paths.get(FILE_NAME), StandardOpenOption.CREATE, StandardOpenOption.WRITE)) { fileChannel.transferFrom(socketChannel, 0, Long.MAX_VALUE); } } } } }
Client sending file:
public class NioClient { private static final int PORT = 1234; private static final String HOST = "localhost"; private static final String FILE_NAME = "image.jpg"; public static void main(String args[]) throws IOException { InetSocketAddress serverAddress = new InetSocketAddress(HOST, PORT); try (SocketChannel socketChannel = SocketChannel.open(serverAddress)) { try (FileChannel fileChannel = FileChannel.open(Paths.get(FILE_NAME))) { fileChannel.transferTo(0, fileChannel.size(), socketChannel); } } } }
In this way, you can transfer videos, pictures and archives.