Creating nested directories on server using JSch in Java

前端 未结 3 1655
谎友^
谎友^ 2020-12-11 10:35

I am making an application for file uploading in Java using jSch. I want to put my file in different directories based on their creation date etc.

I hav

相关标签:
3条回答
  • 2020-12-11 11:10

    Finally, I've done it.

    This is how I got succeed :

    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);
            }
    
    0 讨论(0)
  • 2020-12-11 11:11

    I don't think what you want to do is possible in the SFTP protocol. You will have to create each sub-directory in turn.

    0 讨论(0)
  • 2020-12-11 11:12
        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();
        }
    }
    

    I used this implementation to create nested folders.

    I tried not to use Exception. Keep in mind that filesystem is linux based. The OP already found a solution but I wanted to append to it. Simply I do mkdir if the folder that I wanted to create doesn't exist in "ls" result.

    0 讨论(0)
提交回复
热议问题