因此,我正在開發讀取包含一些數據的JSON文本文件的android應用程序。我在文本文件(here)中有一個300 kb(307,312字節)的JSON。我還開發桌面應用程序(cpp)來生成和加載(和解析)JSON文本文件。不同數量的字符在Java Android InputStream和C++ ifstream中
當我嘗試在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應用程序,我把在res /我JSON文本文件的原始文件夾。當我嘗試打開並使用InputStream讀取時,字符串的長度只有291,896。我無法解析它(我使用相同的C++代碼使用jni解析它,也許它不重要)。
InputStream is = getResources().openRawResource(R.raw.textfile);
byte[] b = new byte[is.available()];
is.read(b);
in_str = new String(b);
UPDATE:
我也有嘗試使用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")
。還是行不通。