2016-11-29 63 views
0

因此,我正在开发读取包含一些数据的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")。还是行不通。

回答

0

好的,我找到了解决方案。它是ASCIIUTF-8问题。

here:每个码点

  • UTF-8可变长度编码,1-4个字节。 ASCII值使用1个字节编码为ASCII。
  • ASCII单字节编码

我的文件大小为307312个字节,基本上我需要的字符每个字节。所以,我需要将文件编码为ASCII。

当我使用C++ ifstream时,字符串大小为307,312。 (相同数量的字符,如果它是用ASCII编码

同时,当我使用的Java InputStream,该字符串大小为291896。我认为这是因为读者正在使用UTF-8编码。

那么,如何使用get ASCII编码在Java

通过this线程和this文章中,我们可以在Java中使用InputStreamReader并将其设置为ASCII。这里是我的完整代码:

String in_str = ""; 
try{ 
    InputStream is = getResources().openRawResource(R.raw.textfile); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "ASCII")); 
    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); 
    } 
}catch(Exception e){ 
    e.printStackTrace(); 
} 

如果你有同样的问题,希望这会有所帮助。干杯。