【问题标题】:Different Number of Character in Java Android InputStream and C++ ifstreamJava Android InputStream和C ++ ifstream中的不同字符数
【发布时间】: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


    【解决方案1】:

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

    来自here

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

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

    当我使用 C++ ifstream 时,字符串大小为 307,312。 (如果使用 ASCII 编码,则与数字字符相同)

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

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

    通过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();
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-06
      • 2012-05-27
      • 2014-12-29
      • 2018-11-05
      • 2013-12-09
      • 2011-03-03
      • 1970-01-01
      • 2011-12-28
      相关资源
      最近更新 更多