This question is related to the following answer posted by Zon.
Transfer folder and subfolders using channelsftp in JSch?
I used the following code to copy a folder from remote to local.
public void downloadDir(String sourcePath, String destPath) throws SftpException { // With subfolders and all files.
// Create local folders if absent.
try {
new File(destPath).mkdirs();
} catch (Exception e) {
System.out.println("Error at : " + destPath);
}
sftpChannel.lcd(destPath);
// Copy remote folders one by one.
lsFolderCopy(sourcePath, destPath); // Separated because loops itself inside for subfolders.
}
private void lsFolderCopy(String sourcePath, String destPath) throws SftpException { // List source (remote, sftp) directory and create a local copy of it - method for every single directory.
Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(sourcePath); // List source directory structure.
for (ChannelSftp.LsEntry oListItem : list) { // Iterate objects in the list to get file/folder names.
if (!oListItem.getAttrs().isDir()) { // If it is a file (not a directory).
if (!(new File(destPath + "/" + oListItem.getFilename())).exists() || (oListItem.getAttrs().getMTime() > Long.valueOf(new File(destPath + "/" + oListItem.getFilename()).lastModified() / (long) 1000).intValue())) { // Download only if changed later.
new File(destPath + "/" + oListItem.getFilename());
sftpChannel.get(sourcePath + "/" + oListItem.getFilename(), destPath + "/" + oListItem.getFilename()); // Grab file from source ([source filename], [destination filename]).
}
} else if (!".".equals(oListItem.getFilename() || "..".equals(oListItem.getFilename())) {
new File(destPath + "/" + oListItem.getFilename()).mkdirs(); // Empty folder copy.
lsFolderCopy(sourcePath + "/" + oListItem.getFilename(), destPath + "/" + oListItem.getFilename()); // Enter found folder on server to read its contents and create locally.
}
}
}
But I am getting a null pointer exception at the following line which I am unable to resolve.
Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(sourcePath); // List source directory structure
I get that it has problem reading the source path but why? Please suggest.
Edited:
This is the stacktrace:
Exception in thread "main" 4:
at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1720)
at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1526)
at org.gradle.CopyTest.downloadDir(CopyTest.java:68)
at org.gradle.CopyTest.main(CopyTest.java:97)
Caused by: java.lang.NullPointerException
at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1543)
... 3 more
This exception is getting thrown:
throw new SftpException(SSH_FX_FAILURE, "", (Throwable)e);
From this statement I believe:
((MyPipedInputStream)io_in).updateReadSide();