Android 保存和加载字符串和布尔值的 1D 和 2D 数组



好的,所以在观看和阅读了几个关于将标准变量保存和加载到内部存储/从内部存储加载的教程后,我完全感到困惑。基本上,我找不到任何有用的参考资料,这将告诉我更多关于这一点的信息。因为我没有使用Java的IOStream的经验,所以我正在寻找一些教程来解释我需要的一切,所以我会知道我在做什么,而不仅仅是复制+粘贴代码,没有人关心为什么。感谢您的所有建议。

所以总结一下我想要的 - 我有字符串数组和布尔值的 2D 数组(字符串 foo[500]; 布尔布尔值[10][20]),我想做的是保存它并将其加载到内部存储中/从内部存储加载。此外,在此 IO 流开始之前,我需要检查文件是否存在 - 如果不存在,请创建它们。

您必须使用字节缓冲区将变量存储到字节流中,然后将此缓冲区写入文件中。您必须导入以下内容:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

这是一个 3 步操作:1 分配缓冲区,2 将数据写入缓冲区,3 将缓冲区写入文件:

// First you have to calculate the size of your strings in bytes
int size = 0;
// Assuming string is encoded in ASCII, so one byte for each
// character, else you have to multiply the string size by the size
// of a encoded character
for (int i = 0; i < 500; i++)
    size += foo[i].length();
// Allocating the buffer, 10 * 20 is your boolean array size, because
// one boolean take one byte in memory
ByteBuffer buffer = ByteBuffer.allocate(size + 10 * 20);
// Put your strings into your buffer
for (int i = 0; i < 500; i++)
    buffer.put(foo[i].getBytes());
// To store boolean we will store 0 for false and 1 for true
for (int i = 0; i < 10; i++)    {
    for (int j = 0; j < 20; j++)
        buffer.put((byte) (bool[i][j] ? 1 : 0));
}
// And finally write your buffer into your file
try {
    // If file doesn't exist, it will be created
    FileOutputStream fos = openFileOutput("file", MODE_PRIVATE);
    // buffer.array is a 1D array of the bytes stored in the buffer
    fos.write(buffer.array());
    fos.close();
} catch (IOException e) {
    e.printStackTrace();
}

听起来你可以用"共享首选项"完成所有工作。您可以使用"共享首选项"来保存任何原始数据。

以下内容详细介绍了实现,还包括要查看的文件 API 和外部存储解决方案:http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html

最新更新