如何在将文件上传到远程服务器后使用java删除目录?

时间:2014-05-20 19:52:52

标签: java ftp-client

我的问题是需要将文件从一个远程服务器传输到另一个远程服务器(可能是FTP / SFTP),但没有直接的方法将文件从一个远程服务器传输到另一个远程服务器。

这就是我将文件从服务器下载到本地临时的原因。 上传到本地到另一台服务器后。上传后我需要删除本地临时文件夹,但文件和文件夹不会被删除。

在这方面你能帮助我们吗?

我的代码是

    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


    }

4 个答案:

答案 0 :(得分:3)

您可以使用Apache FTPClient执行此操作以及FTP所需的所有其他常用命令。

删除文件夹的示例:

FTPClient client = new FTPClient();
client.connect(host, port);
client.login(loginname, password);
client.removeDirectory(directoryPathOnServer);
client.disconnect();

答案 1 :(得分:1)

这是一个代码片段,删除目录的所有内容和目录本身..

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);

}

答案 2 :(得分:0)

如果您要删除系统中的目录

这是一个例子的一部分:

File x=new File("C:\Users\satyamahesh\folder");
String[]entries = x.list();
for(String s: entries){
    File currentFile = new File(x.getPath(), s);
    currentFile.delete();
}

然后删除您的文件夹。

如果您想测试成功或者没有成功下载文件夹

请测试Ad Fundum的答案。

答案 3 :(得分:0)

删除文件夹的示例: (@SatyaMahesh在此部分中,您的代码不正确,此代码使用的NIO是正确的。):

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{
  Path path = Paths.get("data/subdir/logging-moved.properties");
  try {
    Files.delete(path);
  } catch (IOException e) {
    //deleting file failed
    e.printStackTrace();
  }
}

然后删除您的文件夹。