服务器文件操作之ChannelSftp的使用方法

前言:此api的具体文档参考:ChannelSftp文档

1.常用方法
put(): 文件上传
get(): 文件下载
cd(): 进入指定目录
ls(): 得到指定目录下的文件列表
rm(): 删除指定文件

2.java案例

package com.test01;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author Min.Z
 * @create 2021/4/21
 * @since 1.0.0
 */
public class testend {
    private static final int connectTimeout = 30000;

    public static void main(String[] args) {
        //文件名
        String fileName = "zhoumin.txt";
        //服务器文件路径
        String path = "/min/ap/ecsp/";
        //服务器ip
        String host = "192.168.43.218";
        //服务器端口号
        int port = 22;
        //服务器登录用户名
        String user = "min";
        //服务器用户密码
        String password = "123";
        //要保存的文件:路径+名字
        String saveLocalFile = "D:\\abc.txt";
        //要生成本地的文件:路径+名字
        String createLocalFile = "D:\\zhou123.txt";
        //要删除本地的文件的路径
        String localPath = "D:\\Temp\\";

        /**
         * 读取文件内容返回byte数组
         */
        byte[] array = download(fileName, path, host, port, user, password);
            try {
            //将文件的byte的数组转为String类型,
            System.out.println(new String(array, "utf-8"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        /**
         * 下载文件到本地
         */
        boolean fileExist = downloadLocal(saveLocalFile, fileName, path, host, port, user, password);
        System.out.println("文件是否存在=="+fileExist);
        //读取下载后的本地文件
        if (fileExist) {
            readLocalFile(saveLocalFile);
        }


        //创建并写入本地文件
        File file = writeLocalFile(createLocalFile);
        /**
         * 上传文件到服务器
         */
        uploadLocalFile(file, path, host, port, user, password);


        /**
         * 根据文件创建时间删除文件
         */
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-04-21 16:20:00");
            //删除本地文件
            deleteLocalFile(localPath, date);
            removeDateFile(date, path, host, port, user, password);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public static boolean stringIsNotEmpty(String str) {
        return null != str && str.length() != 0;
    }

    /**
     * @return 读取文件内容返回byte数组
     */
    public static byte[] download(String fileName, String path, String host, int port, String user, String password) {
        Session session = null;
        ChannelSftp channel = null;//ChannelSftp类是JSch实现SFTP核心类
        try {
            JSch jsch = new JSch();
            if (port == 0) {
                session = jsch.getSession(user, host);
            } else {
                session = jsch.getSession(user, host, port);
            }
            session.setPassword(password);
            //禁用StrictHostKeyChecking选项会使连接的安全性低于启用该选项的安全性,
            // 因为它可以让您连接到远程服务器而无需验证其SSH主机密钥.如果启用该选项,
            // 则只能连接到SSH客户端已知密钥的服务器
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(connectTimeout);
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect(connectTimeout);

            if (!(path == null || path.trim().length() == 0)) {
                channel.cd(path);//进入指定目录
            }
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            channel.get(fileName, outputStream);//文件下载,文件不存在报错 2: No such file
            byte[] arrayOfByte = outputStream.toByteArray();
            return arrayOfByte;
        } catch (SftpException e) {
            if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {//2: No such file
                // file doesn't exist
                throw new RuntimeException(fileName+"文件不存在");
            } else {
                throw new RuntimeException(e);//这个一定要捕捉异常,不然代码报错,为没有返回值
            }
        } catch (Exception e0) {
            throw new RuntimeException(e0);
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }

    /**
     * 下载文件到本地
     * @saveLocalFile 保存到本地的文件 路径+文件名
     * @return 是否存在文件
     */
    public static boolean downloadLocal(String saveLocalFile, String fileName, String path, String host, int port, String user, String password) {
        Session session = null;
        ChannelSftp channel = null;
        boolean fileExist = true;//文件存在
        try {
            JSch jsch = new JSch();
            if (port == 0) {
                session = jsch.getSession(user, host);
            } else {
                session = jsch.getSession(user, host, port);
            }
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(connectTimeout);
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect(connectTimeout);

            if (!(path == null || path.trim().length() == 0)) {
                channel.cd(path);//进入指定目录
            }
            File file = new File(saveLocalFile);
            if (file.exists()) {
                file.delete();
            }

            FileOutputStream fos = new FileOutputStream(file);
            channel.get(fileName,fos);//get()文件下载,文件不存在时会报错
        } catch (SftpException e) {
            if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {//2: No such file
                fileExist = false;
            } else {
                throw new RuntimeException(e);//这个一定要捕捉异常,不然代码报错,为没有返回值
            }
        } catch (Exception e0) {
            throw new RuntimeException(e0);
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
            return fileExist;
        }
    }


    /**
     * 读取本地文件
     * @param saveLocalFile  文件路径+文件名
     */
    public static void readLocalFile(String saveLocalFile) {
        File file = new File(saveLocalFile);
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String line;
            while (stringIsNotEmpty(line = br.readLine())) {//一行一行的读取
                System.err.println(line);
            }
            fis.close();
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建并写入本地文件
     * @param createLocalFile  文件路径+文件名
     */
    public static File writeLocalFile(String createLocalFile) {
        File file = new File(createLocalFile);
        try {
            //①设置编码方式
//            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "GBK"));

            //②不设置编码方式
            BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
            bw.write("我是java");
            bw.newLine();//换行,在不同的系统中会展示不同的符号,如果在Linux上不要读取到^M,则不应使用这种换行方式,直接在字符后面接\n
            bw.write("哇,哇哇");
            bw.newLine();
            bw.write("结束来了来了");
            bw.flush();//刷新缓冲流,把数据写进该文件。如果存在for循环,一定要在for循环里添加bw.flush()
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 按条件删除本地文件
     * @param localPath  文件路径
     */
    public static void deleteLocalFile(String localPath,Date date) {
        File file = new File(localPath);
        for (String fileName : file.list()) {
            try {
                String pfile = localPath + fileName;//当前文件完整路径
                FileTime fileTime = Files.readAttributes(Paths.get(pfile), BasicFileAttributes.class).creationTime();//文件创建时间
                if (fileTime.toMillis() < date.getTime()) {//date大于创建时间
                    File f = new File(pfile);
                    if (!f.isDirectory()) {//非文件夹
                        System.out.println("删除文件==="+fileName);
                        f.delete();//文件删除
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 上传文件到服务器
     */
    public static void uploadLocalFile(File file, String path, String host, int port, String user, String password) {
        Session session = null;
        ChannelSftp channel = null;
        try {
            JSch jsch = new JSch();
            if (port == 0) {
                session = jsch.getSession(user, host);
            } else {
                session = jsch.getSession(user, host, port);
            }
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(connectTimeout);
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect(connectTimeout);

            if (!(path == null || path.trim().length() == 0)) {
                channel.cd(path);//进入指定目录
            }
            InputStream is = new FileInputStream(file);
            channel.put(is, file.getName());
            is.close();
        } catch (Exception e0) {
            throw new RuntimeException(e0);
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }

    /**
     * 根据时间删除服务器上的文件
     */
    public static void removeDateFile(Date date, String path, String host, int port, String user, String password) {
        Session session = null;
        ChannelSftp channel = null;
        Vector vector = null;
        try {
            JSch jsch = new JSch();
            if (port == 0) {
                session = jsch.getSession(user, host);
            } else {
                session = jsch.getSession(user, host, port);
            }
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(connectTimeout);
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect(connectTimeout);

            if (!(path == null || path.trim().length() == 0)) {
                channel.cd(path);//进入指定目录
                vector = channel.ls(path);//获取文件目录下所有的文件
            }

            for (Object item : vector) {
                ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) item;
                if (!entry.getAttrs().isDir()) {
                    String fileName = entry.getFilename();
                    if (".".equals(fileName) || "..".equals(fileName)) {
                        continue;
                    }
                    Date date1 = new Date(entry.getAttrs().getMTime() * 1000L);
                    if (date1.getTime() < date.getTime()) {
                        channel.rm(path + fileName);
                    }
                }
            }
        } catch (Exception e0) {
            throw new RuntimeException(e0);
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容