package com.inspect.base.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

import org.apache.commons.net.ftp.FTPClient;

public class SFTPUtilByFtp4J {
    private String username;
    private String password;
    private String privateKey;
    private String host;
    private int port;
    private String targetFilePath;
    FTPClient client = new FTPClient();

    public SFTPUtilByFtp4J(String username, String password, String host, int port, String targetFilePath) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
        this.targetFilePath = targetFilePath;
    }

    public boolean login() {
        boolean bln = false;

        try {
            this.client.connect(this.host, this.port);
            this.client.login(this.username, this.password);
            if (this.client.isConnected()) {
                bln = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bln;
    }

    public boolean upload(String path) {
        boolean bln = false;

        try {
            this.client.storeFile("", Files.newInputStream(new File(path).toPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bln;
    }

    public String download(String filename) {
        InputStream inputStream = null;
        String s = "";

        try {
            System.out.println("-------待下载的文件地址11-------" + filename);
            inputStream = this.client.retrieveFileStream(filename);
            System.out.println("-------下载后的文件流长度-------" + inputStream.available());
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            inputStream.close();
            s = new String(bytes, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return s;
    }

    public static void main(String[] args) {
        String username = "xgftp";
        String password = "Xg369246$";
        String host = "10.10.18.17";
        int port = 21;
        String targetFilePath = "D:\\test\\123.xml";
        SFTPUtilByFtp4J ftp4J = new SFTPUtilByFtp4J(username, password, host, port, targetFilePath);
        boolean flag = ftp4J.login();
        if (flag) {
            System.out.println("=============成功");
        } else {
            System.out.println("=============失败");
        }

        ftp4J.download("/home/xgftp/xml/hmzx.xml");
    }
}
