【问题标题】:How to delete directory using java after uploading files to Remote Server?将文件上传到远程服务器后如何使用java删除目录?
【发布时间】:2014-05-20 19:52:51
【问题描述】:

我的问题是需要将文件从一台远程服务器传输到另一台远程服务器(可能是 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


    }

【问题讨论】:

  • 当将文件从 SFTP 服务器传输到另一个 SFTP 服务器时,该文件夹被删除。当一个服务器是 FTP 时,我无法删除文件和文件夹。请给我解决方案/建议。

标签: java ftp-client


【解决方案1】:

这里是一段代码sn -p,删除目录和目录本身的所有内容..

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】:

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

    删除文件夹示例:

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

    【讨论】:

    • 我无法直接传输文件,这就是我从一台服务器下载到本地并上传到另一台服务器的原因。
    【解决方案3】:

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

    这是示例的一部分:

    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 的答案。

    【讨论】:

    • 请使用名为 NIO 的新 I/O API,File 已过时。
    • 文件没有过期。它仍然是 Java API 的一部分。
    【解决方案4】:

    删除文件夹的示例:(@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();
      }
    }
    

    然后你的文件夹就被删除了。

    【讨论】:

    • 请使用名为 NIO 的新 I/O API,File 已过时。
    • 您可以使用文件来删除一些文件夹。
    • @Zabuza 其实我知道如何使用 NIO Files.delete(), Files.createDirectory(), Paths.get()。或者,您可以使用 blah-blah-blah.delete() 之类的文件。所以你的评论没有多大意义。此外,Java 7 类似于 Java 8或者您的评论不正确,因为我工作过,您可以像添加 一样编辑您的评论,但或者这是更正粗体字NIO的对,删除你的File is outdated。您发表评论 like 这个问题,不要发布 cmets 喜欢这个答案的问题,使用 File 有什么问题吗?
    猜你喜欢
    • 1970-01-01
    • 2014-09-16
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    相关资源
    最近更新 更多