Java 使用 SharedPreferences 保存字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19556433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving byte array using SharedPreferences
提问by user2453055
So I have a byte [] array
which I have created in my android app. I want to use SharedPreferences from android to store it and retrieve it back again when I start my app.
How can I do that ?
所以我有一个byte [] array
我在我的 android 应用程序中创建的。我想使用 android 的 SharedPreferences 来存储它并在我启动我的应用程序时再次检索它。我怎样才能做到这一点 ?
采纳答案by Francis
You could try to save it has a String
:
您可以尝试将其保存为String
:
Storring the array:
存储数组:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("myByteArray", Arrays.toString(array));
Retrieving the array:
检索数组:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String stringArray = settings.getString("myByteArray", null);
if (stringArray != null) {
String[] split = stringArray.substring(1, stringArray.length()-1).split(", ");
byte[] array = new byte[split.length];
for (int i = 0; i < split.length; i++) {
array[i] = Byte.parseByte(split[i]);
}
}
回答by Zax
Saving an Array in Shared Preferences:
在共享首选项中保存数组:
public static boolean saveArray()
{
SharedPreferences sp = SharedPreferences.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
mEdit1.putInt("Status_size", byteArr.size()); /* byteArr is an array */
for(int i=0;i<byteArr.size();i++)
{
mEdit1.remove("Status_" + i);
mEdit1.putString("Status_" + i, byteArr.get(i));
}
return mEdit1.commit();
}
Loading Array Data from Shared Preferences:
从共享首选项加载数组数据:
public static void loadArray(Context mContext)
{
Shared Preferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(mContext);
byteArr.clear();
int size = mSharedPreference1.getInt("Status_size", 0);
for(int i=0;i<size;i++)
{
byteArr.add(mSharedPreference1.getString("Status_" + i, null));
}
}
Implement and call the above 2 functions. I hope the above code helps
实现并调用上述2个函数。我希望上面的代码有帮助
回答by Daniel Landau
You can save a byte array in SharedPreferences by using android.util.Base64.
您可以使用 android.util.Base64 在 SharedPreferences 中保存一个字节数组。
For saving:
为了节省:
String saveThis = Base64.encodeToString(array, Base64.DEFAULT);
For loading:
装载:
byte[] array = Base64.decode(stringFromSharedPrefs, Base64.DEFAULT);
回答by Ariel Yust
You actually enlarge the size of a datawhen you convert it to a Base64 String.
当您将数据转换为 Base64 字符串时,您实际上会放大数据的大小。
the final size of Base64-encoded binary data is equal to 1.37 times the original data size + 814 bytes (for headers).
Base64 编码的二进制数据的最终大小等于原始数据大小的 1.37 倍 + 814 字节(对于标头)。
It's faster and memory efficient to save a byte[] in the SharedPreferences using Charsets.ISO_8859_1
使用Charsets.ISO_8859_1在 SharedPreferences 中保存 byte[] 更快且内存效率更高
private static final String PREF_NAME = "SharedPreferences_Name";
private static final String DATA_NAME = "BytesData_Name";
public static byte[] getBytes(Context ctx) {
SharedPreferences prefs = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
String str = prefs.getString(DATA_NAME, null);
if (str != null) {
return str.getBytes(Charsets.ISO_8859_1);
}
return null;
}
public static void setBytes(Context ctx, byte[] bytes) {
SharedPreferences prefs = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor e = prefs.edit();
e.putString(DATA_NAME, new String(bytes, Charsets.ISO_8859_1));
e.commit();
}
- ISO_8859_1 Preserves your data (unlike UTF-8 and UTF-16)
- If you are going to transfer these bytes outside the app, using a JSON for example, then you will have to convert the byte[] to Base64 before serializing them.
- JSON won't be able to understand the weird characters ISO_8859_1 will be using.
- ISO_8859_1 保留您的数据(与 UTF-8 和 UTF-16 不同)
- 如果要在应用程序外部传输这些字节,例如使用 JSON,则必须在序列化它们之前将 byte[] 转换为 Base64。
- JSON 将无法理解 ISO_8859_1 将使用的奇怪字符。
TIP: if you want to save on more space (in case your saving huge byte[]) compress the byte[] before you convert it to any format (ISO or Base64)
提示:如果您想节省更多空间(以防您保存大字节 []),请在将字节 [] 转换为任何格式(ISO 或 Base64)之前对其进行压缩
回答by meechum
I couldn't upvote Ariel Yust's answer but it worked perfectly.
我无法支持 Ariel Yust 的回答,但它运行得很好。
Other answers (like Base64 encoder) were not available for my minimum API version or did not preserve the original value (that can be problematic when encrypting / decrypting data)
其他答案(如 Base64 编码器)不适用于我的最低 API 版本或未保留原始值(在加密/解密数据时可能会出现问题)
As an addition I advise to use extensions in kotlin :
另外,我建议在 kotlin 中使用扩展:
val String.toPreservedByteArray: ByteArray
get() {
return this.toByteArray(Charsets.ISO_8859_1)
}
val ByteArray.toPreservedString: String
get() {
return String(this, Charsets.ISO_8859_1)
}
Then you simply call it on your string :
然后你只需在你的字符串上调用它:
val string = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE).getString("string", "") ?: ""
val byteArray = string.toPreservedByteArray