Java Android Inputstream和C ifstream中的不同数量的字符

Different Number of Character in Java Android InputStream and C++ ifstream

本文关键字:字符 Inputstream Android ifstream Java      更新时间:2023-10-16

因此,我正在开发读取包含一些数据的JSON文本文件的Android应用程序。我在文本文件中有一个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。我无法解析它(我使用具有相同C 代码的JNI对其进行解析,也许并不重要)。

InputStream is = getResources().openRawResource(R.raw.textfile);
byte[] b = new byte[is.available()];
is.read(b);
in_str = new String(b);

更新:

我也尝试使用这种方式。

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);
}

即使,我尝试将其从Java Android Project中的Res/Raw文件夹转移到资产文件夹。当然,我将InputStream行更改为InputStream is = getAssets().open("textfile.txt")。仍然不工作。

好吧,我找到了解决方案。它是 ascii utf-8 问题。

从这里:

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

我的Filesize是307,312字节,基本上我需要拿每个字节。因此,我需要将文件编码为ascii。

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

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

那么,如何使用 ascii java

编码

通过此线程和本文,我们可以在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();
}

如果您有同样的问题,希望这会有所帮助。欢呼。