user2821894 user2821894 - 1 year ago 69
Java Question

How to avoid hardcoding in java

I have read many articles on avoiding hardcoding in java. But could not get clear idea on how to apply it on my requirement.After doing some research am asking this question. Below is my code snippet. In that I want to avoid the hardcoding of the path name in Process pr = rt.exec().Any suggestions on how to do it.Thanks in advance.

public class StartUp {

String executable = getStringValue("");
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

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

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;


Answer Source

You have severals things to try:


private Properties _properties;

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

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

and the properties file will be similar to

But you can also use SPRING CONTEXT

    <property name="locations">
    <property name="ignoreResourceNotFound" value="true"/>

and the elements inside will be accessed that way



For your concrete problem.

You can create a file\\server\\rd.exe

and then after the init you do calls to getStringValue:

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

Then you can do the rt.exec and instead of using hardcoded strings, you can use the ones you retrieve before.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download