Created
April 28, 2016 01:37
-
-
Save Tgo1014/5afd83799a6208fa1c7aa16422e18c81 to your computer and use it in GitHub Desktop.
Send a file from Android to Java Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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