[英]Does Java have something similar to Cocoa's NSUserDefaults?
Mac OS X and iOS have a nice little class called NSUserDefaults
. Mac OS X和iOS有一个不错的小类NSUserDefaults
。 It's a singleton that lets you store strings, arrays, and primitives, and you can always implement some methods to add custom objects to it. 它是一个单例,可让您存储字符串,数组和基元,并且始终可以实现一些方法来向其中添加自定义对象。 It's super useful when you need to store a quick setting without dealing with file manipulations (for example, storing the last picked font name). 当您需要存储快速设置而不处理文件操作(例如,存储最后选择的字体名称)时,此功能非常有用。
Does Java have something simple like this? Java有这样简单的东西吗? I'd like to be able to store a user's last settings to reload a similar state when the program reloads, but I'm not sure what the best way to do this is in Java. 我希望能够存储用户的上一次设置,以便在程序重新加载时重新加载类似的状态,但是我不确定用Java最好的方法是什么。
Yes, you can use the java.util.prefs API . 是的,您可以使用java.util.prefs API 。 How do I save preference user settings in Java? 如何在Java中保存首选项用户设置? and What is the best way to save user settings in java application? 和在Java应用程序中保存用户设置的最佳方法是什么? have some helpful info. 有一些有用的信息。 To get you started: 为了帮助您入门:
[[NSUserDefaults standardUserDefaults] setString:@"some string" forKey:@"some_key"];
becomes 变成
Preferences prefs = Preferences.userNodeForPackage(this);
prefs.put("some_key", "some string");
and 和
[[NSUserDefaults standardUserDefaults] stringForKey:@"some_key"];
becomes 变成
Preferences prefs = Preferences.userNodeForPackage(this);
prefs.get("some_key");
No. The closest thing is the property file system. 否。最接近的是属性文件系统。 You can have a property file (which is a key-value file). 您可以有一个属性文件(它是键值文件)。 Generally, they need to be in the classpath of the java program you're running. 通常,它们需要位于您正在运行的Java程序的类路径中。 You can also create property files (or xml files) anywhere you want to in the file system (like a known good place). 您还可以在文件系统中想要的任何位置(例如已知的好地方)创建属性文件(或xml文件)。 NSUserDefaults uses something like a p-list stored somewhere in the your home directory's Library, using a standard naming an directory path. NSUserDefaults使用标准目录命名方式,使用存储在主目录库中某处的p列表之类的东西。 You would have to come up with your own standard in Java. 您将不得不提出自己的Java标准。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.