Arun Arun - 1 month ago 7x
Java Question

Server socket file transfer

I have used server socket concept in java to transfer files like images and videos. But when i receive at the client side, i am customizing the file names. Can i get the original name of the file as it is?

For Example:

If the file from server end for transfer is "abc.txt", i need this same name to be reflected in the client end(without passing the name separately).

In the server end:

public class FileServer {
public static void main (String [] args ) throws Exception {
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {

Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
OutputStream os = sock.getOutputStream();
new FileServer().send(os);

public void send(OutputStream os) throws Exception{
// sendfile
File myFile = new File ("C:\\User\\Documents\\abc.png");
byte [] mybytearray = new byte [(int)myFile.length()+1];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);,0,mybytearray.length);

In the client end:

public class FileClient{
public static void main (String [] args ) throws Exception {

long start = System.currentTimeMillis();

// localhost for testing
Socket sock = new Socket("",13267);
InputStream is = sock.getInputStream();
// receive file
new FileClient().receiveFile(is);
long end = System.currentTimeMillis();


public void receiveFile(InputStream is) throws Exception{
int filesize=6022386;
int bytesRead;
int current = 0;
byte [] mybytearray = new byte [filesize];

FileOutputStream fos = new FileOutputStream("def");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead =,0,mybytearray.length);
current = bytesRead;

do {
bytesRead =, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

bos.write(mybytearray, 0 , current);


Yes, simply transfer the metadata (in your case myFile.getName()) before the actual file contents, and make client and server read and emit that metadata. It's a good idea to use established protocols, for example HTTP and its Content-Disposition header.