Need help with making a settings file - java

I am trying to make an application launcher that has a settings file that will save 'names' for programs and the path to that program, and when you type the name in an input box it will run the program that name is assigned to.
Also if it the name entered is not known by the application (in the settings file) it will ask the user to add the path and will save that name with the user set path in the settings file.
What I need to know is the best way for me to do this and read/write the file, and the easiest way to organize the settings file to be interpreted.
Any suggestions?

You could use java.util.Properties - it stores key/value pairs in a textfile, and is fairly easy to instantiate. e.g:
Properties mySettings = new Properties();
mySettings.load(new FileInputStream("myapp.cfg"));
// getProperty() returns a String
filepath1 = mySettings.getProperty("filePath1");
Then you simply save your settings in myapp.cfg, either directly (it's a simple textfile with key=value pairs), or via mySettings.store(...). The contents of myapp.cfg will look something like this:
# comment and date added by the Properties object
filePath1=/usr/bin/share/filename
otherVar=52

Related

How to write a data into the application.properties file in java

I am working on some automation stuff, in which I just want to write the values into the application.properties file as shown below:
project.ids = 01234, 56789, 14587,...
So here, my key(project.ids) will be the same, I just want to append the ids to the previously stored values (shown above). Whenever my service will be called a new project id will be generated so I just want to append or store the value in the property file to the same key(project.ids).
Could anyone help or suggest here how can I achieve this?
Any suggestions around how to write the value to the application.properties file in Java?
I would suggest to use the Environment class of Spring. But it is only used to read properties and not write them.
what you could do is follow this way:
Load the .properties file:
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("application.properties");
prop.load(in);
Get the value as it is of the property
String ids = prop.getProperty("project.ids");
Set the new value
String ids = prop.setProperty("project.ids", ids + ", 12324...");
PS: I wouldn't play around with the .properties file much, it is mostly used for configurations. Try saving your ids in a DB, Spring can be very helpful for that.

How to create a File object with a String

In my TestClass I want to read the txt-file. I am always very confused how I should go about getting a reference to the txt-file though. The example I dug out of the internet suggested using a BufferedReader which requires a Path object to instantiate. I thought I'd create a File object and invoke it's .toPath(). But now how do I instantiate my File object? The least scary of its constructors require a string, but which string?
The easiest way to reference the file path within the scope of your project would be to use the System properties. Using the below value would return to you the users current working directory. Something like this would do the trick:
File file = new File (System.getProperty ("user.dir") + "/" + path_to_txt_file);
Depending on your system you may need to modify the delimiter.

Java File - Append pre-defined filename to a user-defined directory

I have a program that creates multiple output files e.g. daily_results.txt, overall_results.txt etc.
I want to allow the user to specify the directory that these files will be saved to using JFileChooser.
So if the user selected the directory they wanted their output to be saved to as "C:\temp\". What is the best way to append daily_results.txt to that file object. Is there a more elegant way to do this other than:
File file = new File(userDirectory.getPath() + "daily_results.txt");
Any ideas?
Apologies!
I think this can quite easily be accomplished with the JFileChoosers setSelectedFile method.

Print system property name if property not found in property file

I have 2 property files:
application.properties
config.properties
Both of these fiels contains properties in it.
I am loading properties of these fiels by setting system properties in IBM websphere server.
During application startup all properties in both of these files are loaded through ApplicationProperty.java class.
private static Properties applicationProperties = new Properties();
readPropertyFileOne(...){
properties.load(new FileInputStream(propertiesLocationOne));
}
readPropertyFileTwo(...){
properties.load(new FileInputStream(propertiesLocationTwo));
}
Now after application starts and read all properties in both files. If I tried to access any property in file through this code
findNonNullableProperty(String aPropertyName){
String value = properties.getProperty(aPropertyName);
if(value == null){
//print system property name here. Name can be propertiesLocationOne or propertiesLocationTwo. But what is that? I want to know file location.
}
}
and it return null.
UPDATE: after evaluating your question again I understand this: You want to get a property value form your own property class. If the property value returns null you want to know which property file holds the key and print out the name of the property file.
The answer to this is that you can't do this. If you read the javadoc for the properties class, you fine that the get("KEY_NAME") method return null only if put an unknown key in. For a empty value you get "", an empty string. As the key is not known it can't be in either of your files. You can't decide which file name to print (or you have to print both).
If you want to do this for the empty strings ("") you have to add more information in your own property class. The java.util.Properties class uses a hash map to store the key value pairs. After loading the pairs from the file the name of the file isn't available any longer. So you needs to store the file name somewhere.
Next problem is that you load keys from two files into one hash map. Once inside the table you can't decide from which file they where read. Two possible solutions:
you add the file name to the key: if you do this in the property file itself it's easy, but you then have to know the file name to get the value.
you hold one property for each file: then you have to look into both properties when someone ask fro a value. However this can be wrapped in your Property class, so the user don't know this.
Just get property from System class:
public class PrintPropery {
public static void main(String[] args) {
System.out.println(System.getProperty("app.property"));
}
}

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

Categories

Resources