How to use Java JSch library to read remote file line by line?

做~自己de王妃 提交于 2019-12-04 03:05:06

To manipulate files through ssh, you're better off using sftp than scp or pure ssh. Jsch has built-in support for sftp. Once you've opened a session, do this to open an sftp channel:

ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");

Once you've opened an sftp channel, there are methods to read a remote file which let you access the file's content as an InputStream. You can convert that to a Reader if you need to read line-by-line:

InputStream stream = sftp.get("/some/file");
try {
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    // read from br
} finally {
    stream.close();
}

Using try with resources syntax, your code might look more like this:

try (InputStream is = sftp.get("/some/file");
     InputStreamReader isr = new InputStreamReader(stream);
     BufferedReader br = new BufferedReader(isr)) {
    // read from br
}

JSch library is the powerful library that can be used to read file from SFTP server. Below is the tested code to read file from SFTP location line by line

        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession("user", "127.0.0.1", 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword("password");
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;

            InputStream stream = sftpChannel.get("/usr/home/testfile.txt");
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }

            } catch (IOException io) {
                System.out.println("Exception occurred during reading file from SFTP server due to " + io.getMessage());
                io.getMessage();

            } catch (Exception e) {
                System.out.println("Exception occurred during reading file from SFTP server due to " + e.getMessage());
                e.getMessage();

            }

            sftpChannel.exit();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        }

Please refer the blog for whole program.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!