【问题标题】:How to check directory is existed before creating a new directory in JSCH在 JSCH 中创建新目录之前如何检查目录是否存在
【发布时间】:2012-10-23 13:23:52
【问题描述】:

如何在使用 JSCH SFTP API 创建新目录之前检查目录是否存在?我正在尝试使用lstat,但不确定它是否能完成我需要的工作。提前致谢

【问题讨论】:

    标签: java directory jsch


    【解决方案1】:

    这就是我在JSch 中检查目录是否存在的方式。

    如果目录不存在则创建目录

    ChannelSftp channelSftp = (ChannelSftp)channel;
    String currentDirectory=channelSftp.pwd();
    String dir="abc";
    SftpATTRS attrs=null;
    try {
        attrs = channelSftp.stat(currentDirectory+"/"+dir);
    } catch (Exception e) {
        System.out.println(currentDirectory+"/"+dir+" not found");
    }
    
    if (attrs != null) {
        System.out.println("Directory exists IsDir="+attrs.isDir());
    } else {
        System.out.println("Creating dir "+dir);
        channelSftp.mkdir(dir);
    }
    

    【讨论】:

    • Af 因为我记得attrs 在找不到目录时不会为空。它抛出一个异常。
    • @SRy: 是的,但我在声明时已将 null 分配给它,因此如果未抛出异常 attrs 值不会为 null
    • 我认为您的代码没有按预期工作。因为当上面的代码在没有目录存在的情况下抛出异常时,您假设控制权将到达else 块,控制权不可能到达If-else 块。所以你的代码只有在 attrs 不是 nul 时才有效
    • "attrs = channelSftp.stat(currentDirectory+"/"+dir);" 中会抛出异常在 try catch 块下的行。稍后它将继续进行 if else 部分。如果 attrs 值没有改变(为空),那么它将转到 else 部分并创建目录
    • 我认为异常是急切的,它可以更具体:try{`channel.stat(folderName);`}catch (SftpException e ){`if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE ){` ` channel.mkdir(folderName);` ` }` ` else {` ` throw e;` ` }` }
    【解决方案2】:

    在这种情况下,最好只进行创建并处理错误。这样操作是原子的,并且在 SSH 的情况下,您还可以节省大量的网络流量。如果你先做测试,那么会有一个时间窗口,在此期间情况可能会发生变化,无论如何你都必须处理错误结果。

    【讨论】:

    • 但是我只能创建一次目录。之后,当用户将文件上传到我们的应用程序到该目录时,我必须检查目录是否存在。那么,有没有其他方法可以做到这一点?
    • @Srinivas 当然你只能创建一次。之后你会得到一个错误。处理它。正如我上面所说的。
    • 是的,明白了。谢谢,我之前没听懂。现在明白了,谢谢。
    【解决方案3】:

    我在这里在更广泛的背景下重复相同的答案。检查目录是否存在并创建新目录的特定行是

                SftpATTRS attrs;
                try {
                    attrs = channel.stat(localChildFile.getName());
                }catch (Exception e) {
                    channel.mkdir(localChildFile.getName());
                }
    

    注意。 localChildFile.getName() 是您要检查的目录名称。整个类附在下面,它以递归方式将目录的文件或内容发送到远程服务器。

    import com.jcraft.jsch.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.*;
    
    /**
     * Created by krishna on 29/03/2016.
     */
    public class SftpLoader {
    private static Logger log = LoggerFactory.getLogger(SftpLoader.class.getName());
    
    ChannelSftp channel;
    String host;
    int    port;
    String userName ;
    String password ;
    String privateKey ;
    
    
    public SftpLoader(String host, int port, String userName, String password, String privateKey) throws JSchException {
        this.host = host;
        this.port = port;
        this.userName = userName;
        this.password = password;
        this.privateKey = privateKey;
        channel = connect();
    }
    
    private ChannelSftp connect() throws JSchException {
        log.trace("connecting ...");
    
        JSch jsch = new JSch();
        Session session = jsch.getSession(userName,host,port);
        session.setPassword(password);
        jsch.addIdentity(privateKey);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        log.trace("connected !!!");
        return (ChannelSftp)channel;
    }
    
    public void transferDirToRemote(String localDir, String remoteDir) throws SftpException, FileNotFoundException {
        log.trace("local dir: " + localDir + ", remote dir: " + remoteDir);
    
        File localFile = new File(localDir);
        channel.cd(remoteDir);
    
        // for each file  in local dir
        for (File localChildFile: localFile.listFiles()) {
    
            // if file is not dir copy file
            if (localChildFile.isFile()) {
               log.trace("file : " + localChildFile.getName());
                transferFileToRemote(localChildFile.getAbsolutePath(),remoteDir);
    
            } // if file is dir
            else if(localChildFile.isDirectory()) {
    
                // mkdir  the remote
                SftpATTRS attrs;
                try {
                    attrs = channel.stat(localChildFile.getName());
                }catch (Exception e) {
                    channel.mkdir(localChildFile.getName());
                }
    
                log.trace("dir: " + localChildFile.getName());
    
                // repeat (recursive)
                transferDirToRemote(localChildFile.getAbsolutePath(), remoteDir + "/" + localChildFile.getName());
                channel.cd("..");
            }
        }
    
    }
    
     public void transferFileToRemote(String localFile, String remoteDir) throws SftpException, FileNotFoundException {
       channel.cd(remoteDir);
       channel.put(new FileInputStream(new File(localFile)), new File(localFile).getName(), ChannelSftp.OVERWRITE);
    }
    
    
    public void transferToLocal(String remoteDir, String remoteFile, String localDir) throws SftpException, IOException {
        channel.cd(remoteDir);
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = new BufferedInputStream(channel.get(remoteFile));
    
        File newFile = new File(localDir);
        OutputStream os = new FileOutputStream(newFile);
        BufferedOutputStream bos = new BufferedOutputStream(os);
    
        log.trace("writing files ...");
        int readCount;
        while( (readCount = bis.read(buffer)) > 0) {
            bos.write(buffer, 0, readCount);
        }
        log.trace("completed !!!");
        bis.close();
        bos.close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 2011-05-12
      • 1970-01-01
      相关资源
      最近更新 更多