0

I'm new to Java and is trying to learn the class Properties. I have came up with the code below. However, when I run the code, I noticed that the three properties store in random.txt is in the reverse order of code execution. Why is this the case? Could someone please enlighten me? Thanks in advance for any help!

Properties p1 = new Properties();
    try (OutputStream os1 = new FileOutputStream("random.txt")){
        p1.setProperty("1", "one");
        p1.setProperty("2", "two");
        p1.setProperty("3", "three");
        p1.store(os1, "comment");
    } catch(IOException e){
        e.printStackTrace();
    }

3 Answers3

2

Properties class is used to maintain lists of values in which the key is a String and the value is also a String. The Properties class extends the Hashtable class.

And the iteration order of a hash-based set is undefined in JDK.

However you can pull values from the properties file in the original order by creating your own subclass of Properties and overriding put() and setProperty() method.

FallAndLearn
  • 4,035
  • 1
  • 18
  • 24
1

Note that Properties works with (extends) Hashtable.

Maps are inherently "unordered".

If you want to learn more and really store data ordered, please check out this link How can I write Java Properties in a defined order. This question has been answered before :)

Community
  • 1
  • 1
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
1

Can you call store after each setProperty, like stated above, The data type which store is using is probably LIFO(last in first out), and therefore the last thing to be set is the first thing saved.

Try calling store after each set property!