Guest User

Untitled

a guest
Nov 13th, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. package main;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.net.URL;
  6. import java.net.URLConnection;
  7. import java.nio.file.Path;
  8. import java.nio.file.Paths;
  9. import org.apache.commons.net.ftp.FTPClient;
  10. import org.apache.commons.net.ftp.FTPReply;
  11.  
  12. public class Uploader{
  13.  
  14. private static final int BUFFER_SIZE=4096;
  15. private static final String ftpUrl="ftp://%s:%s@%s/%s;type=i";
  16. //FTP credentials
  17. private static final String host="";
  18. private static final String user="";
  19. private static final String pass="";
  20.  
  21. //local directory to sync, e.g. "C:\\xampp\\htdocs\\"
  22. public static final Path localBase=Paths.get("");
  23.  
  24. public static void upload(Path f){
  25. try{
  26. URL u=new URL(String.format(ftpUrl,user,pass,host,localBase.relativize(f).toString().replace('\\','/')));
  27. URLConnection conn=u.openConnection();
  28. OutputStream o=conn.getOutputStream();
  29. FileInputStream i=new FileInputStream(f.toFile());
  30. byte[] buffer=new byte[BUFFER_SIZE];
  31. int bytesRead=-1;
  32. while((bytesRead=i.read(buffer))!=-1){
  33. o.write(buffer,0,bytesRead);
  34. }
  35. i.close();o.close();
  36. }catch(IOException e){
  37. e.printStackTrace();
  38. }
  39. }
  40.  
  41. public static void delete(Path f){
  42. FTPClient ftpClient=new FTPClient();
  43. try{
  44. ftpClient.connect(host,21);
  45. if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))return;
  46. if(!ftpClient.login(user,pass))return;
  47. ftpClient.deleteFile(localBase.relativize(f).toString().replace('\\','/'));
  48. }catch(IOException ex){
  49. ex.printStackTrace();
  50. }finally{
  51. try{
  52. if(ftpClient.isConnected()){
  53. ftpClient.logout();
  54. ftpClient.disconnect();
  55. }
  56. }catch(IOException ex){
  57. ex.printStackTrace();
  58. }
  59. }
  60. }
  61.  
  62. public static String getFTPPath(){
  63. return String.format(ftpUrl.substring(0,14),user,pass,host);
  64. }
  65.  
  66. }
Add Comment
Please, Sign In to add comment