java使用jsch连接linux处理文件

发布时间 2023-12-08 11:22:36作者: sowler

1、Maven依赖

        <!--Java连接Linux服务器依赖-->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>

2、相关实现

private static final String RECORD_DIR="/dings";
    private static final String SAVE_DIR="D:/backGroundVideos";
    public static void main(String[] args){
        // SFTP服务器地址
        String host = "xxx.xxx.xxx.xxx";
        // SFTP服务器端口号
        int port = Integer.valueOf("22");
        // SFTP登录用户名
        String username = "xxx";
        // SFTP登录密码
        String password = "xxxxx";
        JSch jsch = new JSch();
        Session session = null;
        ChannelSftp channelSftp = null;
        try {
            session = jsch.getSession(username, host, port);
            session.setPassword(password);
            // 设置StrictHostKeyChecking为no,避免第一次连接时会提示确认主机指纹信息
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();
            // 切换到要操作的文件夹路径
            channelSftp.cd(RECORD_DIR);
            Vector<ChannelSftp.LsEntry> fileList = channelSftp.ls("./*");
            for (int i=0; i < fileList.size(); i++) {
                ChannelSftp.LsEntry entry = fileList.elementAt(i);
    
                if (!entry.getAttrs().isDir()) {

                    InputStream inputStream = channelSftp.get(entry.getFilename());
  
                    File file = new File(SAVE_DIR + "/local_directory/");
                    if (!file.exists()){
                        file.mkdirs();
                    }
                    String filePath = file +File.separator+ entry.getFilename();
                    OutputStream outputStream = new FileOutputStream(filePath);
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
       
                    inputStream.close();
                    outputStream.flush();
                    outputStream.close();
                }
                //获取完成删除文件
                //channelSftp.rm(entry.getFilename());
            }
        } catch (JSchException | SftpException  | IOException e) {
            e.printStackTrace();
        } finally {
            if (channelSftp != null && channelSftp.isConnected()) {
                channelSftp.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }