Pregunta

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 have a main directory "/var/local/recordingsbackup/" in which I am creating other directories and putting data in them.

To achieve this:

  • I have to create Dir'y like "/var/local/recordingsbackup/20140207/root/SUCCESS/WN/" and put data in it.

I've tried this so far:

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();
        }
}
  • If I'm creating single dir like /var/local/recordingsbackup/ then no error occurs and files successfully uploaded.

Please help me in this...how can I create these Nested Directories???

¿Fue útil?

Solución

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

Otros consejos

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.

    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.

Correction of the previous script:

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

Another solution is execute shell command:

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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top