Skip to content

Instantly share code, notes, and snippets.

@Tgo1014
Created April 28, 2016 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tgo1014/5afd83799a6208fa1c7aa16422e18c81 to your computer and use it in GitHub Desktop.
Save Tgo1014/5afd83799a6208fa1c7aa16422e18c81 to your computer and use it in GitHub Desktop.
Send a file from Android to Java Server
//first you need to create a socket and connect with a socket then use the following code
private OutputStream out = socket.getOutputStream();;
//you need to use the file you want to send as a param
public void sendMessage(File file) throws IOException {
if (out != null) {
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(bytes);
out.flush();
}
}
//you need to be connected with a socket from where you will receive the files, then use the following code
//stream to receive the files
private StreamConnection mConnection;
InputStream inputStream = mConnection.openInputStream();
ObjectInputStream ois = new ObjectInputStream(inputStream);
//receiving the file
public void receiveFile(){
try {
ois = new ObjectInputStream(inputStream);
byte[] bytes;
FileOutputStream fos = new FileOutputStream("C://temp//yourFile.jpg"); //path to save the file, it can be any extension you want
try {
bytes = (byte[]) ois.readObject();
fos.write(bytes);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
System.out.println("File Received!");
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ProcessConnectionThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ProcessConnectionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment