Reputation: 5316
Is there a way to send a file over sockets in Java? If so how? If not, how does one go around sending a file from one computer to another using java?
Upvotes: 0
Views: 3629
Reputation: 61
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main
{
public static void main(String[] args) throws IOException {
ServerSocket servsock = new ServerSocket(123456);
File myFile = new File("s.pdf");
while (true)
{
Socket sock = servsock.accept();
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
}
}
}
The client module
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class Main {
public static void main(String[] argv) throws Exception
{
Socket sock = new Socket("127.0.0.1", 123456);
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("s.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
}
}
Upvotes: 1
Reputation: 290
If your primary attention lies on sending files from one computer to another. And not on building your own file server and client using a proprietary protocol, you can embed an ftp-server at the server side and an ftp client at the client side within your own java applications.
Upvotes: 0
Reputation: 53684
you open up a socket connection and copy the file bytes into the socket and read the bytes from the other end of the socket. the same way that you send any stream through a socket connection. that said, there's any number of ways to copy a file from one computer to another (using java), including copying to a shared filesystem, ftping the file, http posting the file to a webserver...
Upvotes: 4
Reputation: 5735
Client-Server architecture is most suitable to achieve what you want.
Start FileServer
on the first computer and run FileClient
on the second.
Upvotes: 1