Accessing and encoding of properties files - java

I'm used to work with properties files, for example from Ant. Where I can simply reference the property file doing something like that:
<property file="webapp_DO_NOT_COMMIT.properties"/>
(the file is so named because our DVCS is configured as to never commit files containing "DO_NOT_COMMIT" to prevent committing credentials/passwords/etc.)
Here's a very simple .properties file example:
passwd=brokencleartextpassword
Now I want to put some configuration in another, similar, properties file that I need to access from my Java code. How should I go about it?
I also have another related question: is the character encoding of .properties file defined by any spec?

Put it in the classpath and then load it by java.util.Properties API.
Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.properties"));
As to the encoding, it's ISO-8859-1, as specified in the API javadoc.
... the input/output stream is encoded in ISO 8859-1 character encoding. ...
But you can go around it by feeding a Reader instead (which is new since Java 1.6).
Properties properties = new Properties();
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.properties");
properties.load(new InputStreamReader(input, "UTF-8"));
See also:
Properties tutorial

Related

Is there any way to change a properties file that is in my classpath?

I have a properties file that is in my classpath. My requirement is to change some properties in this file based on some inputs I get from arguments. The nature of arguments decide whether I need to change the properties and if yes which properties to change. The problem is that all classpath entries are loaded at the application startup time, so changing from within my application would not have any effect. How do I overcome this problem?
One possible solution I can think of is to not add this properties file in classpath but add after modifications are done. Is it viable? What can be a good solution?
It doesn't matter whether this file is on your classpath or not. It is a file: if you overwrite its contents, it will have changed. There isn't some in-memory copy that magically gets made at startup. This is very different from classes that are loaded in and which might need change at runtime.
Properties files that adhere to the right format can be read into a java.util.Properties object. You could do that, use the object to alter the properties as needed, then write it back out to the file. Check the store and load methods in that class. Mind that if you use the versions that take an Output/InputStream, the encoding is hard-coded. If the file's encoding is anything else than ISO-8859-1, use a method with an appropriate Writer/Reader.
Depends on how your application is deployed. If your properties files is inside a jar, you won't be able to directly change that properties file since its packaged and zipped up in an archive. You can instead as someone else mentioned load those properties into an object, and then store/write out to an external location, probably a URL based location. URL is convenient because it gets you access to virtually any location and it has that nifty openStream() method for loading properties. Your application could then look for the new file on load, and default to the application startup version if it fails to read/load from the new location.
Here is a sample code:
Properties p = new Properties();
File f = new File("file");
InputStream in = new FileInputStream(f);
p.load(in);
p.put("key", "blah");
OutputStream out = new FileOutputStream(f);
// If no comments p.store(writer);
p.store(out, "properties");
You need to first remove that property from the property file and then re-define it. Their is no way to directly modify the properties file.
Below is an example:
Properties pproperties = new Properties();
if (properties.containsKey("key1")) {
properties.remove("key1");
properties.setProperty("key1", "value1");
properties.store(new FileOutputStream("file.properties"), null);
}

how to search for string in file

How could I search for string in text file in java?
Would it have to be in a text file or could it read a .ini or some other file type
example
sound = off
opengl = on
openal = off
I tried searching for it on google but I couldnt really find anything.
Thanks in advance
It looks like you want to use a Properties file.
You can load one using Properties.load(String path);
If your file is a properties file or an ini file (key = value), you may want to use the Apache Commons Configuration API. It is much better than the Properties class from the JDK.
There are tons of information with those typical of questions.
Here you have two easy examples:
Loading Java Properties Files http://viralpatel.net/blogs/2009/10/loading-java-properties-files.html
How do I load property settings with the Properties class? http://www.jguru.com/faq/view.jsp?EID=581608
In short it is easy to load a file into a Properties object, for example to obtain, in your case, the sound value in a example.properties file:
Properties props = new Properties();
props.load(new FileInputStream("example.properties"));
String isOnOrOff = props.getProperty("sound");

An XML or *.properties file in Java to read the user options (in NetBeans 7.0)

For a tool development, I wish to have basic information such as InputPath, OutputPath, DB server name (username, pwd and DBname) etc configured before the user uses the tool.
Can it be easier to have this information in XML file and read this file from java code? or create an *.properties file and use it.
I am using netbeans 7.0 version.
The idea is to have default information will be used from the file, if the user didnt modify the default info.
Also, the xml which used to store the default info shall be available to the user for updating it.
Thank you,
Ramm
Either approach is quite acceptable.
The Properties class in the standard libraries will allow you to use the properties format or xml format with very few code changes.
The .properties approach
Properties props = new Properties();
props.load(new FileInputStream("user.properties"));
//get a value with a default of NOTDEFINED if there is no value found.
String dbPath = props.getProperty("databasePath","NOTDEFINED");
The .xml approach
Properties props = new Properties();
props.loadFromXML(new FileInputStream("user.properties"));
String dbPath = props.getProperty("databasePath","NOTDEFINED");

Is there default properties file to put configurations into?

Any default properties file which java can automatcially load?
The short answer is no.
The somewhat longer answer starts with a question itself: What should be configured by this file?
For the logging-API of java (java.util.logging) exists a standard-properties-file to configure it. Other frameworks may as well use standard-configuration files. But that always configure only stuff specific for this framework.
If you want to have persistent configuration, you probably want to use the Preference-API. That allows you to save configuration-data, that stays with the user or the JVM.
You can use your own default properties file. You can do it with just few lines.
There is also built in properties, however, these are no simpler, but they are standard.
IMHO Most of the time a plain Proeprties file is used.
This example from the tutorial. This is a more complex example, you can have just one properties file.
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();
// create application properties with default
Properties applicationProps = new Properties(defaultProps);
// now load properties from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
You have to load your properties file yourself or pass arguments at command line.
There is a small library that you can use which will load properties automatically for you: Confucius.

Storing changes in .properties file that has been read via getClass().getResourceAsStream

I am writing a java web application that reads properties from a .properties file. Since I do not know the absolute path of the .properties file, because it depends on the environment the application will run on in the future, I have to load it with "getClass().getResourceAsStream":
Properties props = new Properties();
props.load(getClass().getResourceAsStream("test.properties"));
message = props.getProperty("testdata");
This works as expected. Now I want to change the value for testdata in the file. But I cannot open an Outputstream to write to, because I still don't know the path of the .properties file.
props.setProperty("testdata", "foooo");
props.store(new FileOutputStream("?????"), null);
Is there a way to get the path of the file or can I use the established Properties-object somehow? Any ideas are welcome that allow me to change the .properties file.
You can get an URL by using getResource() rather than using getResourceAsStream()
You can then use that URL to read from and write to your properties file.
File myProps = new File(myUrl.toURI());
FileInputStream in = new FileInputStream(myProps);
Etc.
The Properties class includes a store method that can be used to save the properties back to the stream that was read in getClass().getResourceAsStream("test.properties").

Categories

Resources