【问题标题】:Creating nested directories on server using JSch in Java在 Java 中使用 JSch 在服务器上创建嵌套目录
【发布时间】:2014-03-04 17:42:58
【问题描述】:

我正在使用jSch 制作Java 文件上传应用程序。我想根据创建日期等将我的文件放在不同的目录中。

我有一个主目录"/var/local/recordingsbackup/",我在其中创建其他目录并将数据放入其中。

要实现这一点:

  • 我必须创建 Dir'y like "/var/local/recordingsbackup/20140207/root/SUCCESS/WN/" 然后放 里面的数据。

到目前为止我已经尝试过了:

private void fileTransfer(ChannelSftp channelTarget, temp_recording_log recObj, String filePath) {

        int fileNameStartIndex = filePath.lastIndexOf("/") + 1;
        String date = new SimpleDateFormat("yyyyMMdd").format(recObj.getCalldate());
        String fileName = filePath.substring(fileNameStartIndex);
        String staticPath = "/var/local/recordingsbackup/";
        String completeBackupPath = staticPath + date + "/" + recObj.getUsername() + "/" + recObj.getStatus() + "/" + recObj.getDisposition() + "/";

        try {
            InputStream get = SourceChannel.get(filePath);
            try {
                channelTarget.put(get, completeBackupPath + fileName);
            } catch (SftpException e) {
                System.out.println("Creating Directory...");
                channelTarget.mkdir(completeBackupPath); // error on this line
                channelTarget.put(get, completeBackupPath + fileName);
            }
        } catch (SftpException e) {
            log.error("Error Occured ======== File or Directory dosen't exists === " + filePath);
            e.printStackTrace();
        }
}
  • 如果我正在创建像 /var/local/recordingsbackup/ 这样的单个目录,则不会发生错误并且文件已成功上传。

请帮助我...如何创建这些嵌套目录???

【问题讨论】:

    标签: java jsch mkdir


    【解决方案1】:

    终于,我做到了。

    这就是我成功的方式:

    try {
                channelTarget.put(get, completeBackupPath + fileName);
            } catch (SftpException e) {
                System.out.println("Creating Directory...");
                String[] complPath = completeBackupPath.split("/");
                channelTarget.cd("/");
                for (String dir : complPath) {
                    if (folder.length() > 0) {
                        try {
                            System.out.println("Current Dir : " + channelTarget.pwd());
                            channelTarget.cd(folder);
                        } catch (SftpException e2) {
                            channelTarget.mkdir(folder);
                            channelTarget.cd(folder);
                        }
                    }
                }
                channelTarget.cd("/");
                System.out.println("Current Dir : " + channelTarget.pwd());
                channelTarget.put(get, completeBackupPath + fileName);
            }
    

    【讨论】:

      【解决方案2】:
          public static void mkdirs(ChannelSftp ch, String path) {
          try {
              String[] folders = path.split("/");
              if (folders[0].isEmpty()) folders[0] = "/";
              String fullPath = folders[0];
              for (int i = 1; i < folders.length; i++) {
                  Vector ls = ch.ls(fullPath);
                  boolean isExist = false;
                  for (Object o : ls) {
                      if (o instanceof LsEntry) {
                          LsEntry e = (LsEntry) o;
                          if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
                              isExist = true;
                          }
                      }
                  }
                  if (!isExist && !folders[i].isEmpty()) {
                      ch.mkdir(fullPath + folders[i]); 
                  }
                  fullPath = fullPath + folders[i] + "/";
              }
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      

      我使用这个实现来创建嵌套文件夹。

      我尝试不使用异常。请记住,文件系统是基于 linux 的。 OP 已经找到了解决方案,但我想附加到它。 如果我想创建的文件夹在“ls”结果中不存在,我只需执行 mkdir。

      【讨论】:

        【解决方案3】:

        我认为您想做的事情在 SFTP 协议中是不可能的。您必须依次创建每个子目录。

        【讨论】:

          【解决方案4】:

          更正之前的脚本:

          public static void mkdirs(ChannelSftp ch, String path) {
              try {
                  String[] folders = path.split("/");
                  if (folders[0].isEmpty()) folders[0] = "/";
                  String fullPath = folders[0];
                  for (int i = 1; i < folders.length; i++) {
                      Vector ls = ch.ls(fullPath);
                      boolean isExist = false;
                      for (Object o : ls) {
                          if (o instanceof LsEntry) {
                              LsEntry e = (LsEntry) o;
                              if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
                                  isExist = true;
                              }
                          }
                      }
                      if (!isExist && !folders[i].isEmpty()) {
                          // Add separator path
                          ch.mkdir(fullPath + "/" + folders[i]); 
                      }
                      // Add separator path
                      fullPath = fullPath + "/" + folders[i] + "/";
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
          

          另一种解决方案是执行shell命令:

          String remotePath = "fake/folders/recursive/on/sftp/server";
          
          ChannelExec channel = (ChannelExec) session.openChannel("exec");
          // NOTE: the provided paths are expected to require no escaping
          channel.setCommand("mkdir -p " + remotePath);
          channel.connect();
          while (!channel.isClosed()) {
              // dir creation is usually fast, so only wait for a short time
              Thread.sleep(SHORT_WAIT_MSEC);
          }
          channel.disconnect();
          if (channel.getExitStatus() != 0) {
              throw new IOException("Creating directory failed: "  + remotePath);
          }
          

          【讨论】:

          • 您可能想解释为什么您认为之前的(哪个?)开关需要修复。 + 为什么要使用ls 来检查文件夹是否存在?那是低效的。使用stat
          猜你喜欢
          • 1970-01-01
          • 2013-01-14
          • 2012-11-07
          • 1970-01-01
          • 2012-10-04
          • 2010-10-26
          • 1970-01-01
          • 1970-01-01
          • 2018-09-14
          相关资源
          最近更新 更多