![](/img/trans.png)
[英]Copy a file on remote server from one directory to other using Jsch
[英]Use JSch to put a file to the remote directory and if the directory does not exist, then create it
我想使用Jsch库和SFTP协议将文件复制到远程目录。 如果远程主机上的目录不存在,则创建它。
在API文档http://epaul.github.com/jsch-documentation/javadoc/中 ,我注意到在put方法中存在一种“模式”,但它只是传输模式: - 传输模式, RESUME,APPEND,OVERWRITE之一。
是否有一种简单的方法可以做到这一点,而无需编写自己的代码来检查存在,然后递归创建一个目录?
不是我所知道的。 我使用以下代码来实现相同的目的:
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 );
}
}
}
其中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);
}
如果您使用多个线程连接到远程服务器,则上述答案可能无效。 例如,当sftp.cd执行时,没有名为“folder”的文件夹,但在catch子句中执行sftp.mkdir(文件夹)时,另一个线程创建了它。 更好的方法(当然对于基于unix的远程服务器)是使用ChannelExec并使用“mkdir -p”命令创建嵌套目录。
与具有额外功能的现成抽象方法相同的解决方案:
如果同一文件已存在则删除。
public boolean prepareUpload( ChannelSftp sftpChannel, String path, boolean overwrite) throws SftpException, IOException, FileNotFoundException { boolean result = false; // Build romote path subfolders inclusive: String[] folders = path.split("/"); for (String folder : folders) { if (folder.length() > 0 && !folder.contains(".")) { // This is a valid folder: try { sftpChannel.cd(folder); } catch (SftpException e) { // No such folder yet: sftpChannel.mkdir(folder); sftpChannel.cd(folder); } } } // Folders ready. Remove such a file if exists: if (sftpChannel.ls(path).size() > 0) { if (!overwrite) { System.out.println( "Error - file " + path + " was not created on server. " + "It already exists and overwriting is forbidden."); } else { // Delete file: sftpChannel.ls(path); // Search file. sftpChannel.rm(path); // Remove file. result = true; } } else { // No such file: result = true; } return result; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.