Use JSch to put a file to the remote directory and if the directory does not exist, then create it

核能气质少年 提交于 2020-01-12 01:33:29

问题


I would like to copy a file to the remote directory using Jsch library and SFTP protocol. If the directory on the remote host does not exist, then create it.

In the API doc, http://epaul.github.com/jsch-documentation/javadoc/, I noticed in the put method that there is a kind of "mode" but it is just the transfer mode: - the transfer mode, one of RESUME, APPEND, OVERWRITE.

Is there an easy way to do this without having to write my own code to check the existence and then create a directory recursively?


回答1:


Not as far as I know. I use the following code to achieve the same thing:

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 );
        }
    }
}

where sftp is the ChannelSftp object.




回答2:


This is how I check directory existence in JSch.

Create directory if it doesn't 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);
}



回答3:


Above answer may not work if you connect to remote server with multiple threads. Consider for example when sftp.cd executes there is not folder named "folder" but when executing sftp.mkdir(folder) in catch clause the other thread created it. Better way (of course for unix based remote servers) is to use ChannelExec and create nested directories using "mkdir -p" command.




回答4:


Same solution as a ready abstract method with extra features:

  • work with paths that contain filenames;
  • remove if the same file already exists.

    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;
    }
    


来源:https://stackoverflow.com/questions/12838767/use-jsch-to-put-a-file-to-the-remote-directory-and-if-the-directory-does-not-exi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!