Search code examples
javalan

JAVA file sending system


I am trying to create a program which could send files to another computer on LAN, there are 10 computers in this LAN so I want to send files to the specific one. how can I do that?


Solution

  • The most direct way would be this. There are more efficient ways for sure though.

    The Sending Machine would have to have this.

    Socket socket = new Socket("ipaddress_of_machine", SHARED_PORT);
    OutputStream oStream = new BufferedOutputStream(socket.getOutputStream());
    File file = new File("Path_to_File");
    InputStream iStream = new FileInputStream(file);
    byte[] buffer = new byte[8192];
    for(int readCount = iStream.read(buffer); readCount != -1; readCount = iStream.read(buffer)) {
       oStream.write(buffer, 0, readCount);
    }
    oStream.flush();
    oStream.close();
    iStream.close();
    

    The Receiving machine would have to have something like this.

    ServerSocket serverSocket = new ServerSocket(SHARED_PORT);
    Socket socket = serverSocket.accept();
    InputStream iStream = socket.getInputStream();
    FileOutputStream oStream = new SocketOutputStream("filename");
    byte[] buffer = new byte[8921];
    for(int readCount = iStream.read(buffer); readCount != -1; readCount = iStream.read(buffer)) {
           oStream.write(buffer, 0, readCount);
        }
        oStream.flush();
        oStream.getFD().sync();
        oStream.close();
        iStream.close();