首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android保存和加载String和booleans的一维和2D数组

Android保存和加载String和booleans的一维和2D数组
EN

Stack Overflow用户
提问于 2014-03-04 17:25:04
回答 2查看 753关注 0票数 0

好的,在观看和阅读了一些关于将标准变量保存和加载到内部存储或从内部存储的教程之后,我完全糊涂了。基本上,我找不到任何有用的参考资料,这会告诉我更多。因为我没有使用IOStream的经验,所以我正在寻找一些教程来解释我所需要的一切,所以我将知道我在做什么,而不仅仅是工作的Copy+Paste代码,而且没有人关心为什么。谢谢你的建议。

因此,总结一下我想要的--我有一个字符串数组和一个二维布尔数组(String foo500;bool10 bool10),我想要做的是保存它并将其加载到/从内部存储。此外,在这个IO流启动之前,我需要检查文件是否存在-如果不存在,那么创建它们。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-04 17:45:46

听起来像是你可以用共享的首选项来完成所有的事情。您可以使用SharedPreferences保存任何原始数据。

下面是实现细节,还包括文件API和要查看的外部存储解决方案:http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html

票数 0
EN

Stack Overflow用户

发布于 2014-03-04 18:03:56

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

代码语言:javascript
复制
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

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

代码语言:javascript
复制
// 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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22178763

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档