Java > JSch.如何从设置文件中获取SFTP连接的属性?



我正在使用此代码从服务器下载文件:

 import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelSftp;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    public class Main {
        public static void
 main(String[] args) {
        String host = "hostname";
        String login = "username";
        String password = "pass";
        int port = 22;
        String remoteDirectory = "directoryPath";
        String localDirectory = "directoryPath";

        Session session = null;
        Channel channel = null;
        ChannelSftp sftpChannel = null;
        try{
            JSch jsch = new JSch();
            session = jsch.getSession(login, host, port);
            session.setPassword(password);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            sftpChannel = (ChannelSftp)channel;
            sftpChannel.get(remoteDirectory, localDirectory);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

如您所见,usernamepasswordhostport是硬编码。我需要从我在计算机上拥有的settings.txt文件中获取这些属性,但没有成功地使其成为可能。

settings.txt to your项目的根,并使用此代码加载:

Properties properites = new Properties();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();           
InputStream is = classLoader.getResourceAsStream("/settings.txt");
properties.load(is);

最新更新