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

天大地大妈咪最大 提交于 2019-12-02 22:47:10
Nick Wilson

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.

abi1964

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

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.

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