Java networking : Sending and Receiving file

We can transfer file from one system to another sysem useing java program. here is an example where one program will read file from local machine and sends it to receiving program. Other receiving program copy all contents reciverd from remote progam and writes it to file.

FileSender class is working as client and FileReceiver class working as server. Here , 192.168.0.1 is address of machine where FileReceiver program is running and it can be changed accourding to your machine. 1234 is port number at which server program is listening for client reque

FileSender.java


package network;
import java.io.*;
import java.net.*;
import java.util.*;
public class FileSender{
    public static void main(String ar[])throws Exception{
        Socket clientSocket=new Socket("192.168.0.2",1234);
        //InputStream in=clientSocket.getInputStream();
        OutputStream out=clientSocket.getOutputStream();
        
        //PrintStream ps=new PrintStream(out);
        
        FileInputStream fis=new FileInputStream("F://Test.java");
        int x=0;
        while(true){
            x=fis.read();
            if(x==-1)break;
            out.write(x);
        }
        out.close();
    }
}

FileReceiver.java




package network;
import java.io.*;
import java.net.*;
import java.util.*;
public class FileReceiver{
    public static void main(String ar[])throws Exception{
        ServerSocket ss=new ServerSocket(1234);
        Socket clientSocket=ss.accept();
        InputStream in=clientSocket.getInputStream();
        //OutputStream out=clientSocket.getOutputStream();
        FileOutputStream fos=new FileOutputStream("rec.txt");
        int x=0;
        while(true){
            x=in.read();
            if(x==-1)break;
            fos.write(x);
        }
        fos.close();
    }
}

4 comments:

Rajeev Ulaganathan said...

Hi.. sorry, i have tried your program, but it result an empty file only. . it consists nothing . .

Pls Help me. .

Paddy @ Mexico said...

You have to FLUSH the data before you close the Stream.

fos.flush();

Omkar Kolekar said...

Hi, If i want to send jar file then how it possible through this code? because i tried to send jar file but it is failing in between and sometimes complete file will not be received. please help out in this problem

Omkar Kolekar said...

Hi am trying to send the jar file through this code, sometimes it will not receive full file or sometimes it will fail to transfer please help me out in this problem.

Popular Posts