Login:  Password:    
forgot my password
sign up!
Search: 

File Transfer between 2 computers with Java

In this article we will learn how to transfer files between 2 computers using Java.

29 2

This time we are going to learn how to transfer files between 2 computers. You may transfer any file between any 2 systems in which one system acts as a Server and the other one act as a client. You can implement the logic in making a chat application with file transfer.

Server.java

First we will discuss the coding for server side, we are going to import all the classes which are needed by the Server class:

Listing1 : Importing classes

array0

Here java.net is for importing the ServerSocket and the Socket class. These classes are used for defining the server connection port number and also are used for accepting connections from the client.

Now we define the class along with the main function:

Listing2: Class and main method

public class Server {

	 public static void main (String [] args ) throws IOException {
		 
		    ServerSocket serverSocket = new ServerSocket(15123);

The name of class is Server, we defined a variable serverSocket of ServerSocket type inside the main method. Actually here serverSocket waits for incoming client connection on port 15123 which is specified as argument above (chosen randomly) and accepts the connection when it gets one.

Now we will define the main logic in the program:

Listing3 : Main Logic

		      Socket socket = serverSocket.accept();
		      System.out.println("Accepted connection : " + socket);
		      File transferFile = new File ("Document.doc");
		      byte [] bytearray  = new byte [(int)transferFile.length()];
		      FileInputStream fin = new FileInputStream(transferFile);
		      BufferedInputStream bin = new BufferedInputStream(fin);
		      bin.read(bytearray,0,bytearray.length);
		      OutputStream os = socket.getOutputStream();
		      System.out.println("Sending Files...");
		      os.write(bytearray,0,bytearray.length);
		      os.flush();
		      socket.close();
		      System.out.println("File transfer complete");
		      
	    }
}

Now we explain this:

serverSocket.accept() waits for any client connection and once any clients tries on to connect on server it accepts the connection and then store it in socket object of the Socket class.

We define the file to be transferred as Document.doc in a file variable named transferFile. We define a bytearray which will contain temporary data, define the fin and bin object to read from the transferFile and the data read would be filled in the bytearray object, bin.read method is used to read the file and the data read is stored in the bytearray.

We define a OutStream which here provides a channel to communicate with client side. We write the data read from the bytearray onto the output stream.

We close the objects using the close method.

Client.java

Now we will come to coding at Client side:

First we import all the classes.

Listing4: Import classes

array0

Here java.net is for importing the Socket class. These classes are used for defining the server ip address and the port number of the server.

Now we will define the class and the main method:

Listing5: Defining classes and methods

public class Client {

	public static void main (String [] args ) throws IOException {
	    int filesize=2022386; 
	    int bytesRead;
	    int currentTot = 0;

We defined a class named Client, Main method and a variable filesize which can be thought of like a buffer size.

bytesRead contain the current statistics of the bytes read from the input channel ie inputstream, currentTot contains the total number of bytes read.

Now we will add the processing part:

Listing6: Main Logic

Socket socket = new Socket("127.0.0.1",15123);
	    byte [] bytearray  = new byte [filesize];
	    InputStream is = socket.getInputStream();
	    FileOutputStream fos = new FileOutputStream("copy.doc");
	    BufferedOutputStream bos = new BufferedOutputStream(fos);
	    bytesRead = is.read(bytearray,0,bytearray.length);
	    currentTot = bytesRead;

	    do {
	       bytesRead =
	          is.read(bytearray, currentTot, (bytearray.length-currentTot));
	       if(bytesRead >= 0) currentTot += bytesRead;
	    } while(bytesRead > -1);

	    bos.write(bytearray, 0 , currentTot);
	    bos.flush();
	    bos.close();
	    socket.close();
	  }
}

We defined a Socket object which try to connect on ip 127.0.0.1(local ip in my case, change it when you try on lan with ip of your friends computer) on port number 15123. We define a variable byteArray which will act just like a buffer to hold temporary data, InputStream object called in which will help us to collect all information passed to input channel of client ie files or even the messages which are transferred to client.

We define the FileOutputStream object which point to the file which will be filled with data copied from the server file. The BufferedOutputStream helps us to write data to the output file via a byte array.

We read the data from the inputstream using the read method of the object. The data read from the input channel is stored in the byte array. We initially set currentTot to number of bytes read.

Now we implement a do-while loop. It read again from the input stream and now if the bytesRead is >=0 then we update out currentTot object. When the byteRead is -1 i.e. there is no data left on the inputstream then the do-while loop exits.

After that we write the finally read bytes on the file and then close the stream.

Full Source code:

Listing7: Server code

import java.net.*;
import java.io.*;
public class Server {

	 public static void main (String [] args ) throws IOException {
		 
		    ServerSocket serverSocket = new ServerSocket(15123);
		      Socket socket = serverSocket.accept();
		      System.out.println("Accepted connection : " + socket);
		      File transferFile = new File ("Document.doc");
		      byte [] bytearray  = new byte [(int)transferFile.length()];
		      FileInputStream fin = new FileInputStream(transferFile);
		      BufferedInputStream bin = new BufferedInputStream(fin);
		      bin.read(bytearray,0,bytearray.length);
		      OutputStream os = socket.getOutputStream();
		      System.out.println("Sending Files...");
		      os.write(bytearray,0,bytearray.length);
		      os.flush();
		      socket.close();
		      System.out.println("File transfer complete");
		    }
}

Listing8: Client code

import java.net.*;
import java.io.*;
public class Client {

	public static void main (String [] args ) throws IOException {
	    int filesize=1022386; 
	    int bytesRead;
	    int currentTot = 0;
	    Socket socket = new Socket("127.0.0.1",15123);
	    byte [] bytearray  = new byte [filesize];
	    InputStream is = socket.getInputStream();
	    FileOutputStream fos = new FileOutputStream("copy.doc");
	    BufferedOutputStream bos = new BufferedOutputStream(fos);
	    bytesRead = is.read(bytearray,0,bytearray.length);
	    currentTot = bytesRead;

	    do {
	       bytesRead =
	          is.read(bytearray, currentTot, (bytearray.length-currentTot));
	       if(bytesRead >= 0) currentTot += bytesRead;
	    } while(bytesRead > -1);

	    bos.write(bytearray, 0 , currentTot);
	    bos.flush();
	    bos.close();
	    socket.close();
	  }
}

I hope you liked the article. See you next time.


Anurag Jain
My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified
8 comments have been posted.   Add your comment
[Fechar]

Este post é fechado - você precisa ter acesso ao post para incluir um comentário.

brijesh
Hey, I wanna do the thing u did following the guidelines you provided here but am not getting even a little bit idea of how these two classes named Server and Client are connected to each other. how do they work? where should i put my client class and server class ? is there any setting which should be done in .xml files or something like that before integrating these code to my web application. to be precise am developing a liferay-portlet and i want to develop a portlet for document sharing over a LAN. Any help would be highly appreciated. Thanks and regards Brijesh
[+1 month ago]    Answer it
 
Mr.Bool Editor
We contacted the author of the article and he will answer your question soon.
[+1 month ago]   Answer it
 
Mr.Bool Editor
The author reply is: "Hi Actually, just try with 2 normal computers. Make one of them as server and one as client so that none require authentication.Try with this and check. If this works(which I have tried and works actually) then probably your server is not allowing connections(due to firewall or the authentication procedures you are using). In that case you need to configure the config file of server(not sure what settings you are using) to accept connections from remote host. You need to refer online manual of framework for that. Just try with the test case first ie with 2 normal computer and if it succeeds then work with the firewall settings and configurations. Regards, Anurag Jain"
[+1 month ago]   Answer it
 
Waseem Akram
How to make a system server and a client?is it i have to install a server operating system and connect one client to it in a network? please help me in implementing this thank u warm wishes Waseem Akram
[+1 month ago]    Answer it
 
Mr.Bool Editor
We contacted the author of the article and he will answer your question soon.
[+1 month ago]   Answer it
 
Mr.Bool Editor
Here's the author reply: "There is no special requirement for OS. You can run the Server on any one of normal computer and Client on any other normal computer.Let us know if this works for you :)"
[+1 month ago]   Answer it
 
Dev
how can i run these two files within my system? suppose i want to transfer between two drives location pl suuggest
[6 days ago]    Answer it
 
[author] Anurag Jain
Use below : File file1 =new File("file1.txt"); File file2 =new File("file2.txt"); inStream = new FileInputStream(file1); outStream = new FileOutputStream(file2); byte[] buffer = new byte[1024]; int length; while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); This will write file1.txt into file2.txt
[6 days ago]   Answer it
 
Help us to improve! Give us your feedback:

Give your note to this post: 1 2 3 4 5 6 7 8 9 10
Is this post helpful? Yes No



[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits








mrbool.com
contact us   |   publish your post   |   buy credits

Copyright 2013 - all rights reserved to www.web-03.net