我想使用Jsch库和SFTP协议将文件复制到远程目录.如果远程主机上的目录不存在,则创建它.
在API文档,http://epaul.github.com/jsch-documentation/javadoc/,我注意到在put方法,有一种"模式",但它仅仅是传输模式: -转方式, RESUME,APPEND,OVERWRITE之一.
是否有一种简单的方法可以做到这一点,而无需编写自己的代码来检查存在,然后递归创建一个目录?
Nic*_*son 33
不是我所知道的.我使用以下代码来实现相同的目的:
String[] folders = path.split( "/" );
for ( String folder : folders ) {
if ( folder.length() > 0 ) {
try {
sftp.cd( folder );
}
catch ( SftpException e ) {
sftp.mkdir( folder );
sftp.cd( folder );
}
}
}
Run Code Online (Sandbox Code Playgroud)
其中sftp是ChannelSftp对象.
这是我在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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29643 次 |
| 最近记录: |