【发布时间】:2016-11-29 06:56:29
【问题描述】:
所以,我正在开发读取包含一些数据的 JSON 文本文件的 android 应用程序。我在文本文件 (here) 中有一个 300 kb(307,312 字节)的 JSON。我还开发了桌面应用程序 (cpp) 来生成和加载(和解析)JSON 文本文件。
当我尝试在 c++ 中使用 ifstream 打开并读取它时,我得到了正确的字符串长度 (307,312)。我什至成功解析它。
这是我的 C++ 代码:
std::string json = "";
std::string line;
std::ifstream myfile(textfile.txt);
if(myfile.is_open()){
while(std::getline(myfile, line)){
json += line;
json.push_back('\n');
}
json.pop_back(); // pop back the last '\n'
myfile.close();
}else{
std::cout << "Unable to open file";
}
在我的 android 应用程序中,我将 JSON 文本文件放在 res/raw 文件夹中。当我尝试使用 InputStream 打开和读取时,字符串的长度只有 291,896。而且我解析不出来(我用jni用同样的c++代码解析,也许不重要)。
InputStream is = getResources().openRawResource(R.raw.textfile);
byte[] b = new byte[is.available()];
is.read(b);
in_str = new String(b);
更新:
我也尝试过使用this方式。
InputStream is = getResources().openRawResource(R.raw.textfile);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while(line != null){
in_str += line;
in_str += '\n';
line = reader.readLine();
}
if (in_str != null && in_str.length() > 0) {
in_str = in_str.substring(0, in_str.length()-1);
}
甚至,我尝试将它从 res/raw 文件夹移动到 java android 项目中的 assets 文件夹。当然,我将InputStream 行更改为InputStream is = getAssets().open("textfile.txt")。还是不行。
【问题讨论】:
标签: java android c++ inputstream ifstream