Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.net.URL;
- import java.net.URLConnection;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import org.apache.commons.net.ftp.FTPClient;
- import org.apache.commons.net.ftp.FTPReply;
- public class Uploader{
- private static final int BUFFER_SIZE=4096;
- private static final String ftpUrl="ftp://%s:%s@%s/%s;type=i";
- //FTP credentials
- private static final String host="";
- private static final String user="";
- private static final String pass="";
- //local directory to sync, e.g. "C:\\xampp\\htdocs\\"
- public static final Path localBase=Paths.get("");
- public static void upload(Path f){
- try{
- URL u=new URL(String.format(ftpUrl,user,pass,host,localBase.relativize(f).toString().replace('\\','/')));
- URLConnection conn=u.openConnection();
- OutputStream o=conn.getOutputStream();
- FileInputStream i=new FileInputStream(f.toFile());
- byte[] buffer=new byte[BUFFER_SIZE];
- int bytesRead=-1;
- while((bytesRead=i.read(buffer))!=-1){
- o.write(buffer,0,bytesRead);
- }
- i.close();o.close();
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- public static void delete(Path f){
- FTPClient ftpClient=new FTPClient();
- try{
- ftpClient.connect(host,21);
- if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))return;
- if(!ftpClient.login(user,pass))return;
- ftpClient.deleteFile(localBase.relativize(f).toString().replace('\\','/'));
- }catch(IOException ex){
- ex.printStackTrace();
- }finally{
- try{
- if(ftpClient.isConnected()){
- ftpClient.logout();
- ftpClient.disconnect();
- }
- }catch(IOException ex){
- ex.printStackTrace();
- }
- }
- }
- public static String getFTPPath(){
- return String.format(ftpUrl.substring(0,14),user,pass,host);
- }
- }
Add Comment
Please, Sign In to add comment