Вопрос

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.

Это было полезно?

Решение 3

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);

Другие советы

One other alternative is having properties file (key-value), same like how you did in PHP.

Even though it is command line program you can still have properties file. You may pass file location as command argument (or) place your file relative to class and use relative path to access file.

If your strings don't need to be changed by non-Java developers, you can simply put them all in a separate class, like this:

public final class Texts {
    public static final String MYSTR1 = "str1";
    public static final String MYSTR2 = "str2";
    ...
    private Texts() {} // Prevents instantiation
}

Doing so makes some maintaining tasks easier, for instance:

  • You can refactor the constant name, so that all uses are automatically changed.
  • You can easely find who uses each constant.
  • You can quickly discover what is the constant's value, and you can navigate to it very quickly.

Use a statics class to hold your globals.

public class Statics
{
 public static final String GLOBAL_NAME = "Stuff";
 public static final int GLOBAL_INT = 9999;
}

And access it like this in your classes.

Statics.GLOBAL_NAME
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top