Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete directory using java after uploading files to Remote Server?

My problem is need to transfer files from one remote server to another remote server (may be FTP/SFTP) but there is no direct method to transfer files from one remote server to another.

That's why I am downloading files from server to local temp. After uploading to local to another server. After uploading I need to remove local temp folder but the files and the folder is not deleted.

Can you please help us in this regard?

My code is

    package FTPTransfer;


    import java.io.BufferedOutputStream;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.io.File;
    import java.util.Calendar;

    import org.apache.commons.net.PrintCommandListener;
    import org.apache.commons.net.ftp.FTP;
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.net.ftp.FTPFile;
    import org.apache.commons.net.ftp.FTPReply;

    import com.jcraft.jsch.*;

    public class FtpToSftp
    {
         JSch sftp=null;
         ChannelSftp channelSftp=null;
         Channel channel=null;
         FTPClient ftp = null;
         Session session=null;     
         String SFTP_ROOT="/Mahesh/";
         String FTP_ROOT="/Mahesh/";
         String Local_Dir="./Temp/";
         int count=0;

public void ftpconnect(String host, String user, String pwd) throws Exception{

        ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

                int reply;
                ftp.connect(host);

                if(ftp.isConnected())
                    System.out.println("FTP Connected");

                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    throw new Exception("Exception in connecting to FTP Server");
                }

                ftp.login(user, pwd);
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                ftp.enterLocalPassiveMode();

            }

            public void sftpconnect(String host, String user, String pwd) throws Exception{
                sftp=new JSch();
                session=sftp.getSession(user,host,22);
                session.setPassword(pwd);
                 java.util.Properties config = new java.util.Properties();
                 config.put("StrictHostKeyChecking", "no");
                 session.setConfig(config); 
                session.connect();
                if(session.isConnected())
                    System.out.println("SFTP Session Connected");  
                channel = session.openChannel("sftp");
                channel.connect();

                 if(channel.isConnected())
                      System.out.println("SFTP Channel Connected");
                    channelSftp=(ChannelSftp)channel;



            }

            public void downloadFromFTP()throws Exception {

                File f=new File(Local_Dir);
                if(!f.exists())
                f.mkdir();

                FTPFile[] files = ftp.listFiles(FTP_ROOT);  
                  count=0;
                  OutputStream outputStream=null;
                for (FTPFile fname : files) {  
                 if (fname.getType() == FTPFile.FILE_TYPE) {
                     System.out.println(fname.getName());

                     File downloadFile = new File(Local_Dir+ fname.getName());
                     outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
                     boolean success = ftp.retrieveFile(FTP_ROOT+fname.getName(), outputStream);
                     if(success)
                         count++;
                     else
                         downloadFile.delete();
                 }
                }

                if(count==files.length)
                    System.out.println("Files Downloaded Successfully");
                System.out.println("count:"+count+"files length:"+files.length);
                outputStream.close();

            }

            public void uploadToSFTP() throws Exception{

                Calendar cal = Calendar.getInstance();
                    int year = cal.get(Calendar.YEAR);
                    int month = cal.get(Calendar.MONTH)+1;//0 based
                    String foldername=month+""+year+"/";
                    String fullDirPath=SFTP_ROOT+foldername;

                    SftpATTRS attrs=null;
                    try{
                    attrs=channelSftp.lstat(fullDirPath);
                    }
                    catch(Exception e){

                    }
                     if(attrs==null)
                     {
                    channelSftp.mkdir(fullDirPath);
                    channelSftp.cd(fullDirPath);
                     }

                count=0;
                File f1 = new File(Local_Dir);
                  File list[] = f1.listFiles();
                 for(File fname  : list) {
                       System.out.println(fname);    
                     channelSftp.put(fname+"", fullDirPath+fname.getName(), ChannelSftp.OVERWRITE); 
                      }

                  if(count==f1.length())
                    System.out.println("Files Uploaded Successfully");



            }

       public FtpToSftp() throws Exception{


           System.out.println("Connecting to FTP");
           ftpconnect("10.219.28.110", "webteam", "web$123");
           System.out.println("Connecting to SFTP");
           sftpconnect("10.219.29.61","root" , "leo$123");

           downloadFromFTP();

           if(ftp.logout()){
               ftp.disconnect();
                System.out.println("FTP connection closed");
             }
           uploadToSFTP();
           channelSftp.disconnect();
               }

        public static final void main(String[] args) 
        {

            try{
                    FtpToSftp fs=new FtpToSftp();
                    File file=new File(fs.Local_Dir);
                   if(file.isDirectory())
                   {  
                       File[] files = file.listFiles();
                       for (File f : files)
                        {
                             String fname=f.getName();
                             boolean success=f.delete();  
                             if(success)
                                System.out.println(fname+" file deleted from local");
                        }       
                   }
                   if(file.delete())
                       System.out.println("Temp folder deleted from local");

                  }
            catch(Exception e){
                e.printStackTrace();
            }


        } // end main


    }
like image 607
Satya Mahesh Avatar asked Dec 13 '25 17:12

Satya Mahesh


2 Answers

You can use Apache FTPClient to do this and all other common commands needed with FTP.

Example to delete a folder:

FTPClient client = new FTPClient();
client.connect(host, port);
client.login(loginname, password);
client.removeDirectory(directoryPathOnServer);
client.disconnect();
like image 94
Ad Fundum Avatar answered Dec 15 '25 08:12

Ad Fundum


Here is a code snippet that deletes all the contents of the directory and the directory itself..

private void deleteDirectory(String path,FTPClient ftpClient) throws Exception{
    FTPFile[] files=ftpClient.listFiles(path);
    if(files.length>0) {
        for (FTPFile ftpFile : files) {
            if(ftpFile.isDirectory()){
                logger.info("trying to delete directory "+path + "/" + ftpFile.getName());
                deleteDirectory(path + "/" + ftpFile.getName(), ftpClient);
            }
            else {
                String deleteFilePath = path + "/" + ftpFile.getName();
                logger.info("deleting file {}", deleteFilePath);
                ftpClient.deleteFile(deleteFilePath);
            }

        }
    }
        logger.info("deleting directory "+path);
        ftpClient.removeDirectory(path);

}
like image 20
sharpcodes Avatar answered Dec 15 '25 08:12

sharpcodes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!