mkdirs() and exists()

This commit is contained in:
Shikhar Bhushan
2010-03-25 23:38:25 +01:00
parent 09b93ec11a
commit 2f1b2c4e77
2 changed files with 52 additions and 1 deletions

View File

@@ -24,6 +24,7 @@ import java.io.IOException;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;
public class SFTPClient {
@@ -32,10 +33,12 @@ public class SFTPClient {
private final SFTPEngine sftp;
private final SFTPFileTransfer xfer;
private PathHelper pathHelper;
public SFTPClient(SessionFactory ssh)
throws IOException {
this.sftp = new SFTPEngine(ssh).init();
this.pathHelper = new PathHelper(sftp);
this.xfer = new SFTPFileTransfer(sftp);
}
@@ -83,6 +86,38 @@ public class SFTPClient {
sftp.makeDir(dirname);
}
public void mkdirs(String path)
throws IOException {
final Stack<String> dirsToMake = new Stack<String>();
for (PathComponents current = pathHelper.getComponents(path); ; current = pathHelper
.getComponents(current.getParent())) {
final FileAttributes attrs = exists(current.getPath());
if (attrs == null) {
dirsToMake.push(current.getPath());
} else if (attrs.getType() != FileMode.Type.DIRECTORY) {
throw new SFTPException(current.getPath() + " exists but is not a directory");
} else {
break;
}
}
while (!dirsToMake.isEmpty()) {
mkdir(dirsToMake.pop());
}
}
public FileAttributes exists(String path)
throws IOException {
try {
return sftp.stat(path);
} catch (SFTPException sftpe) {
if (sftpe.getStatusCode() == Response.StatusCode.NO_SUCH_FILE) {
return null;
} else {
throw sftpe;
}
}
}
public void rename(String oldpath, String newpath)
throws IOException {
sftp.rename(oldpath, newpath);

View File

@@ -37,8 +37,12 @@ public class StatefulSFTPClient
return PathComponents.adjustForParent(cwd, path);
}
public synchronized void cd(String dirname) {
public synchronized void cd(String dirname)
throws IOException {
cwd = cwdify(dirname);
if (exists(cwd) == null) {
throw new SFTPException(cwd + ": does not exist");
}
log.info("CWD = " + cwd);
}
@@ -98,6 +102,18 @@ public class StatefulSFTPClient
super.mkdir(cwdify(dirname));
}
@Override
public void mkdirs(String path)
throws IOException {
super.mkdirs(cwdify(path));
}
@Override
public FileAttributes exists(String path)
throws IOException {
return super.exists(cwdify(path));
}
@Override
public void rename(String oldpath, String newpath)
throws IOException {