Java Android Inputstream和C ifstream中的不同数量的字符
Different Number of Character in Java Android InputStream and C++ ifstream
因此,我正在开发读取包含一些数据的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();
}
如果您有同样的问题,希望这会有所帮助。欢呼。
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- Java Android Inputstream和C ifstream中的不同数量的字符