问题
I have experience developing some Android apps, which handily have XML string files where you can store strings. The last time I developed a desktop Java app I hard-coded the strings (for example button titles, labels etc...). I have since learned this is bad practice, and I should store strings in a file.
I am not sure how to go about doing this.
- I am currently developing in Eclipse. Should I just stick a text file in my project folder?
- Is this standard?
- How do you locate the file in the code?
回答1:
Yes, you should use .properties
files and access them using ResourceBundle.
回答2:
Eclipse has a built-in refactoring that you may find useful.
Source->Externalise Strings
This creates a properties file with the strings stored as key/value pairs.
Behind the scenes it is using ResourceBundle
回答3:
I think if you do this it will not be specific to any IDE: See Load resources via a resources file for an overview. The 1st URL states this about where this class looks for the properties files.
See the ResourceBundle class.
The ResourceBundle
will look first for classes and if not found, it will look for properties files. We don't have to specify file names, the ResourceBundle
will construct the file name using the same mechanism used for classes. The file must have the extension .properties
.
The ResourceBundle
try to load the properties file from the current class-path.
If the properties are stored in sub-directory, use .
instead of /
.
回答4:
Take a look at the Javadoc for ResourceBundle
. The API provides a way to fetch strings for locale specific resources.
来源:https://stackoverflow.com/questions/10417275/external-file-for-strings-as-opposed-to-hardcoding-them