java 在JSCH中创建新目录之前如何检查目录是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13202789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:51:46  来源:igfitidea点击:

How to check directory is existed before creating a new directory in JSCH

javadirectoryjsch

提问by SRy

How to check the existence of the directory before creating a new directory using JSCH SFTP API? I am trying to use lstatbut not sure it's doing the job that I need.Thanks in advance

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

回答by AabinGunz

This is how I check directory existence in JSch.

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

Create directory if dir does ont exist

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

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

回答by user207421

In situations like this it is always better to just do the create and handle the error. That way the operation is atomic, and in the case of SSH you also save a lot of network traffic. If you do the test first, there is then a timing window during which the situation may change, and you have to handle error results anyway.

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

回答by Krishna Sapkota

I am repeating the same answer here in the broader context. The particular lines to check if the directory exists and make a new directory is

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

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

Note. the localChildFile.getName()is the directory name that you want to check. The whole class is attached below that sends a file or content of a directory recursively to the remote server.

笔记。的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();
}