I have a question about storing a UUID. I would like to use Java to generate a UUID and save it so that I can retrieve it the next time the application runs.
In a .NET application I built, I'm doing something similar to this. I'm using the Windows Registry to store the UUID and all other settings. However, this Java application is supposed to be cross-platform compatible. This presents the problem. Obviously on other operating systems I won't have the Windows Registry for such a task, so how would I go about this?
I have one solution for this problem, but I'd like something slightly more sophisticated. My current solution is storing a text file (named something like unique.txt
) in the application's directory and then reading it at runtime.
Here are my grievances about that solution:
Here are the conditions I'd like a solution to satisfy:
I have thought about storing the settings file in the root directory (/
on unix and C:\
on Windows); however, in my experience, writing to the root directory typically requires elevated permissions. I also feel like the root directory is not the most appropriate location for this.
If Java has a built in method for doing something like this, I would greatly appreciate someone pointing me in the direction of it. Otherwise, if someone could provide some guidance, that would also be great.
I apologize if this question is a duplicate. I've searched for something like this, but I haven't found an answer. If anything about the question is unclear, please add a comment and I'll try to revise the question to clarify.
Thank you in advance.
The Preferences API should provide what you need. If you want common settings for the entire system, check out systemNodeForPackage
. Something like this (not tested):
class HardwareId {
public UUID read() {
Preferences pref = Preferences.systemNodeForPackage(HardwareId.class);
String uuid = pref.get("UUID", null);
if (uuid == null) {
uuid = UUID.randomUUID().toString();
pref.put("UUID", uuid);
pref.flush();
}
return UUID.fromString(uuid);
}
}