2016-11-29 55 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(); 
} 

如果你有同樣的問題,希望這會有所幫助。乾杯。

相關問題