List of Topics:
Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Transfer a File Between Two Systems in Java?

Data Transfer Between Systems

Condition for Transferring Data Between Two Systems

  • Description: To transfer a file between two systems in Java, socket programming is used. The client sends the file through an `OutputStream`, and the server receives it using an `InputStream`. Additionally, error handling, timeouts, and data integrity are critical for ensuring a successful file transfer. For larger files or more complex data, serialized objects or HTTP-based protocols like REST APIs may also be used.
Sample Source Code
  • # Client.java
    package SocketConnection;

    import java.io.File;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.nio.file.Files;

    public class FileTransferClient {
    public static void main(String args[]) {
    String host = "localhost";
    int port = 1234;
    try (Socket socket = new Socket(host, port)) {
    File file = new File("path-to-your-file");
    byte[] byteArray = Files.readAllBytes(file.toPath());
    OutputStream outputStream = socket.getOutputStream();
    outputStream.write(byteArray);
    outputStream.flush();
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    }
    # Server.java
    package SocketConnection;

    import java.io.File;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.nio.file.Files;

    public class FileTransferServer {
    public static void main(String args[]) {
    int port = 1234;
    try (ServerSocket serverSocket = new ServerSocket(port)) {
    System.out.println("Server is listening on port " + port);
    try (Socket socket = serverSocket.accept()) {
    InputStream inputStream = socket.getInputStream();
    byte[] byteArray = inputStream.readAllBytes();
    File file = new File("received-file");
    Files.write(file.toPath(), byteArray);
    }
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    }
Screenshots
  • STEP 1: The client initiates a connection with the server and sends the file.
  • Client File Sent

  • STEP 2: The server accepts the incoming connection and saves the received file.
  • Server Receiving File

  • STEP 3: The file is successfully received and stored on the server.
  • File Received on Server

Related Links