加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何避免在java中进行硬编码

发布时间:2020-12-15 04:14:19 所属栏目:Java 来源:网络整理
导读:我已经阅读了很多关于避免使用 java硬编码的文章.但无法清楚地了解如何将其应用于我的要求.经过一些研究后我就提出了这个问题.以下是我的代码段.在那我想避免在进程pr = rt.exec()中的路径名的硬编码.任何关于如何做的建议? public class StartUp {String e
我已经阅读了很多关于避免使用 java硬编码的文章.但无法清楚地了解如何将其应用于我的要求.经过一些研究后我就提出了这个问题.以下是我的代码段.在那我想避免在进程pr = rt.exec()中的路径名的硬编码.任何关于如何做的建议?

public class StartUp {

String executable = getStringValue("executable.run");
    String filein = getStringValue("incoming.file");
    String params1 = getStringValue("executable.params1");
    String params2 = getStringValue("executable.params2");
    String log = getStringValue("log.file");
String ss = "Started";
public String startCommand() throws IOException,InterruptedException{



Runtime rt = Runtime.getRuntime();
//Process pr = rt.exec("C:serverrd.exe -a C:file.lic -z[+] // C:Filelog.txt");

Process pr = rt.exec(executable+" "+params1+" "+filein+" "+params2+" "+log);
    BufferedReader input = new BufferedReader(new InputStreamReader 
(pr.getInputStream()));

String line=null;
StringBuffer start= new StringBuffer();
    while((line=input.readLine()) != null) {
                start.append("ServerStarted" + line + "n");
        System.out.println(line);
}

int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
return line;



//return start.toString();
}
private static String getStringValue(String string) {
    return string;

}
}

解决方法

你有几件事要尝试:

java PROPERTIES

private Properties _properties;

private void init(){
     _properties = new Properties();
     InputStream configurationFileIS = PropertiesConfigurationHandler.class.getClassLoader().getResourceAsStream(CONFIGURATION_FILE);
     _properties.load(configurationFileIS);
}

public String getStringValue(String path) {
    return _properties.getProperty(path);
}

和属性文件将类似

an.element.to.be.configured.like.a.path=/dev/null

但您也可以使用SPRING CONTEXT

<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>WEB-INF/classes/config/properties/database.properties</value>
            <value>classpath:config/properties/database.properties</value>
        </list>
    </property>
    <property name="ignoreResourceNotFound" value="true"/>
</bean>

并且将以这种方式访问??database.properties中的元素

"${jdbc.username}"

为你的具体问题.

您可以创建文件constants.properties

executable.run=C:serverrd.exe
incoming.file=C:file.lic
executable.params=-z
log.file=C:Filelog.txt

然后在init之后调用getStringValue:

String executable = getStringValue("executable.run");
String filein = getStringValue("incoming.file");
String params = getStringValue("executable.params");
String log = getStringValue("log.file");

然后你可以使用rt.exec而不是使用硬编码字符串,你可以使用之前检索的字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读