在Java中使用JSch在服务器上创建嵌套目录[英] Creating nested directories on server using JSch in Java

问题描述

我正在使用 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/ 这样的单个目录,则不会发生错误并且文件已成功上传.

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

推荐答案

终于搞定了.

这就是我成功的方式:

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

本文地址:https://www.itbaoku.cn/post/978486.html