I'm storing user data (nothing important, just user ID and xp amount/level) in a properties file. When using prop.store(output, comment) it resets the file completely and then stores the added data. How can I add data without it resetting the entire file?
Each time you use the store() method, it removes the old data and writes the new data.
To prevent this from happening, you must first load your data and then restore it with new data that you want to add.
This code snippet may help you:
Properties prop = new Properties();
prop.load(new FileInputStream(YOUR_PROPERTIE_FILE));
prop.setProperty(key, value);
prop.store(new FileOutputStream(YOUR_PROPERTIE_FILE), COMMENT);
Related
my.properties
#db connection
mongoconnection=mongodb://user:password#host:27017/database?maxPoolSize=1
#serial=vehicleID
077C70=47368
077C71=47367
077C72=47366
Properties properties = new Properties();
properties.load(new FileInputStream("my.properties"));
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String serialNumber = (String) entry.getKey();
String vehicleId = (String) entry.getValue();
}
In for loop I'm getting 'mongoconnection' as key and its respected value.
I want to differentiate 'db connection' and 'serial=vehicleID'
Properties class provide only flat view of all provided key-value pairs, there is no way to differentiate between blocks.
You could write your own parser for the file you are trying to read
I think you can make a tag to set java environment like this:-Dflag=my. and then you can read different file to get different properties by environment.
You could split your properties in two files (serial.properties, connection.properties)bBecause the properties seems to not have any relation between them. One file for the connection. And the other for the serials. This way, you read the serial properties and do your logic, and when you need the database url you read from the other file.
I normally create a properties file with properties that have something in common. For example, translations properties files have his own properties, database connection properties too. This way is easier to edit and find the properties in the future as the project grow.
Hope this helps.
I have a real quick question. I have a Java program in which I use a properties file. The file is used for keeping track of the program's users. My problem is I cannot figure out how to ADD to the file. I know how to set existing properties to a value, but I don't know how to add more properties without over writing the other ones.
I would like the program to 'register' users, so to speak. Whenever a new users 'signs up', I want the program to add a new property containing the new user's information. I run into this problem though:
Example:
File: numOfUsers=0
One user registers. The username is 'c00lGuy'. The program registers this in the file:
File: numOfUsers=1 user1-username=c00lGuy
Another user registers. She decides to call her username 'theGr8Girl'. The program registers this:
File: numOfUsers=2 user2-username=theGr8Girl
The file after the two users registered:
File: numOfUsers=2 user2-username=theGr8Girl
How do I prevent my program from overwriting existing lines in the file? It seems to erase the file's contents, and then add what I tell it to. I don't want it to erase the file's contents.
The code I am using to register the properties:
Properties prop = new Properties();
OutputStream output = null;
int userCount = getUserCount();
userCount++;
try {
output = new FileOutputStream(fileName);
// set the properties value
prop.setProperty("numOfUsers", String.valueOf(userCount));
prop.setProperty("user" + userCount + "-username", username);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null)
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Try something like this:
FileOutputStream out = new FileOutputStream(fileName);
props.setProperty("numOfUsers", 2);
...
props.store(out, null);
out.close();
Properties files aren't really intended for this sort of usage, but if you have a small enough data set it'll work.
The step you are missing is that you need to read the properties from disk, make the changes, then save them back to disk.
Properties props = new Properties();
try{
props.load(inputStream);
} finally {
inputStream.close();
}
props.setProperty(....);
try{
props.store(outputStream);
} finally {
outputStream.close();
}
Just bear in mind that this is not at all suitable for any sort of volume processing. Also, there is a race condition if you have two threads trying to make changes to the properties file at the same time.
If you are looking for a lightweight persistent store, I highly recommend mapdb.
You code is creating a new Properties object each time. Make sure to reuse the old instance when adding a user.
The typical format for a line in this file would be
user=hashedPassword
so use the username as the key and the password as a value. The number of users does not need to be stored, it is just the size of the properties map.
This question already has answers here:
How to use Java property files?
(17 answers)
Java - Properties: Add new keys to properties file in run time?
(1 answer)
Closed 8 years ago.
I have a property file having different data. I need to update the value of a property. How can achieve this using Java?
My property file contains:
# Module Password for Installer
MODULE_PASSWORD=Mg==
# Modules Selected for Installer
ausphur=yes
einfuhr=no
edec=no
emcs=no
ncts=no
suma=no
eas=no
zollager=no
I need to change yes or no values.
Create a FileOutputStream to the properties file and modify the property by using Properties.setProperty(PROPERTY_NAME,PROPERTY_VALUE) and then call store(out,null) on Properties instance
FileOutputStream out = new FileOutputStream("config.properties");
props.setProperty("ausphur", "no");
props.store(out, null);
out.close();
This will help!
Update:
There is no way to keep your comments back since Properties doesn't know about it. If you use java.util.Properties, it is a subclass of Hashtable which doesn't preserve the order of the keys and values the way they are inserted. What you can do is, you can go for LinkedHashMap collection with your own implementation of Properties datastore. But, you have to read the properties from file yourself and put it in LinkedHashMap. To Note, LinkedHashMap preserves the order in which keys are values are put. so, you can iterate the keyset and update the properties file in the same order back. Thus, the order can be preserved
You could use Properties Java class.
It allows you to handle in a very easy way properties files based on (key, value) pair.
Have a look at http://docs.oracle.com/javase/tutorial/essential/environment/properties.html
In particular:
Saving Properties
The following example writes out the application properties from the previous example using Properties.store. The >default properties don't need to be saved each time because they never change.
FileOutputStream out = new FileOutputStream("appProperties");
applicationProps.store(out, "---No Comment---");
out.close();
The store method needs a stream to write to, as well as a string that it uses as a comment at the top of the output.
Try this.
Properties prop = new Properties();
OutputStream output = null;
output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("propertyname", "newValue");
prop.store(output, null);
Use java.util.Properties.
Properties props = new Properties();
FileInputStream fis = new FileInputStream("pathToYourFile");
props.load(fis);
fis.close();
props.setProperty("propName", "propValue");
FileOutputStream fos = new FileOutputStream("pathToYourFile");
props.store(fos, "Your comments");
fos.close();
I am working on a program for launching programs, and am using JFileChooser to let the user select the file, i would like the program to have the path of the last file available the next time the user starts my program, what would be the best way to accomplish this?
Use a properties file which acts similarly to a hashtable. This code should be pretty accurate (needs exception handling).
private void save(String _url){
Properties prop = new Properties();
prop.setProperty("url", _url);
prop.store(new FileOutputStream("file.properties"), null);
}
private String open(){
Properties prop = new Properties();
prop.load(new FileInputStream("file.properties"));
return prop.getProperty("url");
}
Either your program is web based then stored it in session, or write in file.
I need a configuration file (Properties) for this project I'm working on.
The issue is that the Properties instance fails to load from the file (no exceptions, no visible problems) although it can store properly.
Because I have a defaults HashMap, any property that doesn't exist has it's default value placed in the Properties instance, which then stores everything, so that new properties are seamlessly added when the production server is updated.
I've been tracking this bug for hours, and I can't fix it. I've read dozens of questions here on StackOverflow as well as code examples on other sites. Nothing helped.
The one reason I haven't dropped it already and used the DB instead is that the JDBC driver URL, user and password are stored in that file as well. Notice that the file is being read and written to the hard drive.
Since the defaults system puts stuff in place, even if the file doesn't exist when I try to read, after it's saved it appears, but the next run still won't read anything. I noticed the bug after I changed a setting, and checked the file after a few runs, and to my shock, all values were default.
What's currently happening is the following:
1) No matter if the file is there or not, Properties will not load anything.
2) Since there's nothing in the Properties instance, it is filled with defaults.
3) The instance will now save, overwriting the file with the default values.
Here's all the relevant code:
private static Properties getConfig(){
Properties properties = new Properties();
File cfgFile = new File("data/titallus.properties");
try{
if(cfgFile.createNewFile()){
System.out.println("Config file not found. A default config file will be created automatically.");
}
FileReader reader = new FileReader(cfgFile);
FileWriter writer = new FileWriter(cfgFile);
properties.load(reader);
reader.close();
System.out.println(properties); // Debug, always prints '{}'
for(String k : defaults.keySet()){
if(!properties.containsKey(k)){
properties.setProperty(k, defaults.get(k));
}
}
properties.store(writer, "Titallus Configuration File");
writer.close();
}catch(Exception e){
e.printStackTrace();
System.exit(-1);
}
return properties;
}
I have tried everything I could think of, to no avail.
I also have a Properties subclass for multi-language support, which works just fine.
Does anyone have any idea how to fix this, or at least, another approach to this?
FileWriter writer = new FileWriter(cfgFile);
will be erasing your file before you read from it.
You create a FileWriter for the file before you load the file, which clears the existing data.