Nilesh Tupe
Nilesh Tupe

Reputation: 7803

Sending File using sockets in android

I know basic socket programming. I have a code to send strings using sockets in android. I want to learn how to send a file (MP3,image etc) using sockets between two phones.

Upvotes: 2

Views: 7550

Answers (1)

Matt
Matt

Reputation: 5684

This is some code to send a file. It should work just like you would expect outside of Android. I knew I was sending files that were relatively small, so you might want to make more than one pass through a buffer. The File "f" in my example should just be replaced with the File that contains your MP3 or Image or whatever you want to send.

public void sendFile() throws IOException{
    socket = new Socket(InetAddress.getByName(host), port);
    outputStream = socket.getOutputStream();
    File f = new File(path);
    byte [] buffer = new byte[(int)f.length()];
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    bis.read(buffer,0,buffer.length);
    outputStream.write(buffer,0,buffer.length);
    outputStream.flush();

}

Upvotes: 4

Related Questions