Skip to content

Instantly share code, notes, and snippets.

@carl-olin
Created May 14, 2012 10:43
Show Gist options
  • Select an option

  • Save carl-olin/2693246 to your computer and use it in GitHub Desktop.

Select an option

Save carl-olin/2693246 to your computer and use it in GitHub Desktop.
Simple java file transfer
package client;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
public class FileClient {
private Socket s;
public FileClient(String host, int port, String file) {
try {
s = new Socket(host, port);
sendFile(file);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendFile(String file) throws IOException {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
fis.close();
dos.close();
}
public static void main(String[] args) {
FileClient fc = new FileClient("localhost", 1988, "cat.jpg");
}
}
package server;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer extends Thread {
private ServerSocket ss;
public FileServer(int port) {
try {
ss = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
try {
Socket clientSock = ss.accept();
saveFile(clientSock);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveFile(Socket clientSock) throws IOException {
DataInputStream dis = new DataInputStream(clientSock.getInputStream());
FileOutputStream fos = new FileOutputStream("testfile.jpg");
byte[] buffer = new byte[4096];
int filesize = 15123; // Send file size in separate msg
int read = 0;
int totalRead = 0;
int remaining = filesize;
while((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
totalRead += read;
remaining -= read;
System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
}
fos.close();
dis.close();
}
public static void main(String[] args) {
FileServer fs = new FileServer(1988);
fs.start();
}
}
@juanjimenez-pricesmart

Copy link
Copy Markdown

When I run the classes it does nothing
1

@oHoangNgocThai

Copy link
Copy Markdown

Thank a lot, It's work for me

@leviem1

leviem1 commented Nov 30, 2016

Copy link
Copy Markdown

Okay, after attempting to use this in my application I found that there are some minor bugs. It is not a good idea to ignore the return of dos.write() in the client because it may "duplicate" the data. It seems to be resolved in your server file, but for optimization it might be a good idea to use dos.write(byte[] b, int off, int len) in the client.

@LeCodeurSpatial

Copy link
Copy Markdown

You need to run server and client code on different terminals/cmd prompts.
Can compile on same terminal/prompt but, execution needs two different terminals.

@Divyesh24

Copy link
Copy Markdown

both the program is running terminal
but output is not displaying
tell me what type of i/p should be given?

@iamharshit

Copy link
Copy Markdown

i am getting this error
screenshot from 2017-01-18 23 59 08
any suggestions

@NicolaasP

NicolaasP commented Feb 1, 2017

Copy link
Copy Markdown

@iamharshit it might be because 1.png is not a directory i.e /home/(your user name)/Desktop/1.png (if it has been saved to your desktop) so it doesn't know where to look for the file
(just a guess though)

@Govind071995

Copy link
Copy Markdown

How can i save file name that is sent from Client . @CarlEkerot

@TheSamSmith

Copy link
Copy Markdown

@Govind071995 just store it separately and transfer it before the fine content

@AwfulMint

Copy link
Copy Markdown

Pretty Nice m8

@kmursi

kmursi commented Mar 7, 2017

Copy link
Copy Markdown

you don't need to calculate the remining (file size), just read while there is a new line.

@swagatsy

swagatsy commented Jun 5, 2017

Copy link
Copy Markdown

error
I get this error. Any suggestions???

@Perzios

Perzios commented Mar 17, 2018

Copy link
Copy Markdown

How would i modify this to allow for more than one client to be connected to the server and when a client sends a file, the server sends it to the other users.

@canyuns

canyuns commented May 11, 2018

Copy link
Copy Markdown

when I transfer a small file, it work fine.
however, when I transfer a big file, client throws:
java.net.SocketException: Broken pipe

why? hope have a answer, thanks

@SalkinD

SalkinD commented Aug 18, 2018

Copy link
Copy Markdown

change

while (fis.read(buffer) > 0) {
    dos.write(buffer);
}

to

int read;
while ((read=fis.read(buffer)) > 0) {
	dos.write(buffer,0,read);
}

-> now it works

@flashsloth

Copy link
Copy Markdown

Will it make the file read faster if its done using multiple threads using FileChannel?

@Sxubas

Sxubas commented Sep 19, 2018

Copy link
Copy Markdown
int read;
while ((read=fis.read(buffer)) > 0) {
	dos.write(buffer,0,read);
}

Worked for me, thank you very much!

@hoangthan

Copy link
Copy Markdown

What is the filesize in serverside bro ? why did you set it equal 15123 ?

@ThanhSon232

Copy link
Copy Markdown

You guys need to set the size for the buffer as the same as your file, also fileSize, the best solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment