Expand my Community achievements bar.

Applications for the 2024-2025 Adobe Experience Manager Champion Program are open!

Reading file as inputstream from an SFTP server

Avatar

Level 2

Hi Team

 

I am using jsch to fetch a file from SFTP server using JSCH using the below snippet.

the connect is getting succeeded, however the inputstream is not being able to fetched with the file path.

could anybody help me with this.

 

if anybody has any working snippet, please let me know.

 

 Session session = jsch.getSession(user, host, 22);;
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect();
        logger.info("session connected"+session.isConnected());
        Channel channel = session.openChannel("sftp");
        channel.connect();
                logger.info("channel connected"+channel.isConnected());
        ChannelSftp channelSftp = (ChannelSftp)channel;
 
        //ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
        InputStream stream = channelSftp.get("/faresheet/abc.pdf");
        logger.info("stream connected"+stream.available());
        BufferedReader br = new BufferedReader(new InputStreamReader(stream));

 

Regards

Bishnu

1 Reply

Avatar

Community Advisor

Hi, 

This is not a question directly related to AEM, but rather about pure Java code. Therefore, you could also search for an answer outside of this community. Additionally, I suggest double-checking basic aspects such as whether the file exists, if the path is correct, if any exceptions are being thrown, and if you have proper rights.

You could refactor and ensure that no exceptions occur, something like this

Session session = jsch.getSession(user, host, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
logger.info("session connected: " + session.isConnected());

Channel channel = session.openChannel("sftp");
channel.connect();
logger.info("channel connected: " + channel.isConnected());
ChannelSftp channelSftp = (ChannelSftp) channel;

try {
    InputStream stream = channelSftp.get("/faresheet/abc.pdf");
    logger.info("File fetched successfully");

    // Process the input stream here...

    // Close the stream and disconnect the channel
    stream.close();
    channel.disconnect();
    session.disconnect();
} catch (SftpException | IOException e) {
    logger.error("Error fetching file: " + e.getMessage());
}


Also, you could use the method ChannelSftp.ls() to check if the file is accessible. Please look at this thread for more insights: https://stackoverflow.com/questions/35358762/list-all-files-in-remote-server-using-jsch 

 

Hope this helps



Esteban Bustamante