前言:若是咱们须要调用某个方法,其中的参数为可更改,咱们最好是采用配置文件的方式来写,这样便于管理java
好比我在写一个经过SFTP链接服务器的环节apache
public class SFTPUtil { private static Logger log=Logger.getLogger(SFTPUtil.class.getName()); private String host;//服务器链接ip private String username;//用户名 private String password;//密码 private int port=22;//端口号 private ChannelSftp sftp=null; private Session sshSession=null; public SFTPUtil(String host, String username, String password, int port) { this.host = host; this.username = username; this.password = password; this.port = port; } public SFTPUtil(String host, String username, String password) { super(); this.host = host; this.username = username; this.password = password; } /** *ͨ经过SFTP链接服务器 */ public void connect(){ try { JSch jsch=new JSch(); jsch.getSession(username, host, port); //����session sshSession=jsch.getSession(username, host, port); if(log.isInfoEnabled()){ log.info("Session created."); } sshSession.setPassword(password); Properties sshConfig=new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); if(log.isInfoEnabled()){ log.info("Session connected."); } Channel channel=sshSession.openChannel("sftp"); channel.connect(); if(log.isInfoEnabled()){ log.info("Opening channel."); } sftp=(ChannelSftp)channel; if(log.isInfoEnabled()){ log.info("Connected to "+host+"."); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
以key-value的形式写入参数服务器
package com.copote.commons.util; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ConfigurableConstants { public static Log logger = LogFactory.getLog(ConfigurableConstants.class); public static Properties p = new Properties(); /** * 静态读入属性文件到Properties p变量中 */ public static void init() { InputStream in = null; try { in = ConfigurableConstants.class.getClassLoader().getResourceAsStream("config.properties"); if (in != null) p.load(in); } catch (IOException e) { logger.error("load config.properties into Constants error!"); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("close config.properties error!"); } } } } /** * 封装了Properties类的getProperty函数,使p变量对子类透明. * * @param key property key. * @param defaultValue 当使用property key在properties中取不到值时的默认值. */ public static String getProperty(String key) { return p.getProperty(key); } public static void main(String[] args){ ConfigurableConstants.init(); System.out.println(ConfigurableConstants.getProperty("host")); } }