gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:27:47 26 4
gpt4 key购买 nike

我已经阅读了很多关于避免在 Java 中进行硬编码的文章。但是无法清楚地了解如何将其应用于我的要求。在做了一些研究之后我问了这个问题。下面是我的代码片段。因为我想避免在 Process 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:\\server\\rd.exe -a C:\\file.lic -z[+] // C:\\File\\log.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 属性

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:\\server\\rd.exe
incoming.file=C:\\file.lic
executable.params=-z
log.file=C:\\File\\log.txt

然后在初始化之后调用 getStringValue:

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

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

关于java - 如何避免在 Java 中进行硬编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19251324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com