📄 e409. getting and setting java type values in a preference.txt
字号:
A preference node holds only string values. However, the Preferences class has convenience methods that will convert a number of basic Java types to and from strings. For example, Preferences.putByteArray() converts a byte array into a string and then saves the string value. Preferences.getByteArray() converts the string back into an array of bytes.
The types for which there are conversion methods are boolean, int, long, float, double, and byte[]. For all other types, serialization can be used to convert an arbitrary Java type into a byte array (see e44 Serializing an Object).
See also e410 Getting the Maximum Size of a Preference Key and Value.
// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);
// Preference key name
final String PREF_NAME = "name_of_preference";
// Save
prefs.put(PREF_NAME, "a string"); // String
prefs.putBoolean(PREF_NAME, true); // boolean
prefs.putInt(PREF_NAME, 123); // int
prefs.putLong(PREF_NAME, 123L); // long
prefs.putFloat(PREF_NAME, 12.3F); // float
prefs.putDouble(PREF_NAME, 12.3); // double
byte[] bytes = new byte[1024];
prefs.putByteArray(PREF_NAME, bytes); // byte[]
// Retrieve
String s = prefs.get(PREF_NAME, "a string"); // String
boolean b = prefs.getBoolean(PREF_NAME, true); // boolean
int i = prefs.getInt(PREF_NAME, 123); // int
long l = prefs.getLong(PREF_NAME, 123L); // long
float f = prefs.getFloat(PREF_NAME, 12.3F); // float
double d = prefs.getDouble(PREF_NAME, 12.3); // double
bytes = prefs.getByteArray(PREF_NAME, bytes); // byte[]
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -