Search code examples
javastringtexthard-coding

Alternative practice for hard coding text strings in a Java program?


In my program I have lots of string and repeated strings. Is there a way to separate the text strings from the source code. I do not want to hardcode the string within my program.

In PHP I used to have a file with list variables for each string. But because Java is OOP I do not know how to implement the same idea.

My program is a command line program.


Solution

  • If you are using Java 1.7 (SE 7), you can use java.util.Properties. The java documentation provides a good explanation. Here is a code snippet:

    String fileName = "/path/to/file/thePropertiesFileName.properties";
    FileReader reader = new FileReader(fileName);
    Properties prop = new Properties();
    prop.load(reader);