Using JSch, is there a way to tell if a remote file exists without doing an ls?

Viewed 42976

Using JSch, is there a way to tell if a remote file exists without doing an ls and looping through the files to find a name match?

Thanks

6 Answers

This is how I check directory existence in JSch.

Note: not related to this question, but some may find it useful.

Create directory if dir does not 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);
}
import java.util.ArrayList;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class FileExists {

ChannelExec channelExec = null;
static Channel channel = null;

static String host = "hostname";
static String user = "username";
static String password = "password$";

public static void main(String[] args) {
    String filename = "abc.txt";
    String filepath = "/home/toolinst/ggourav";
    try {
        Channel channel = getChannelSftp(host, user, password);
        channel.connect();
        ChannelSftp channelSftp = (ChannelSftp) channel;
        channelSftp.cd(filepath);
        String path = channelSftp.ls(filename).toString();
        if (!path.contains(filename)) {
            System.out.println("File doesn't exist.");
        } else
            System.out.println("File already exist.");

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

}

private static Channel getChannelSftp(String host, String user, String password) {
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, 22);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        config.put("PreferredAuthentications", "publickey,keyboard-interactive,password");
        session.setConfig(config);
        session.setPassword(password);
        session.connect();
        channel = session.openChannel("sftp");

    } catch (Exception e) {
        System.out.println("Failed to get sftp channel. " + e);
    }
    return channel;
}

}

Related