【问题标题】:Can't fit file encoding when writing a file with Chrome File System API使用 Chrome 文件系统 API 写入文件时无法适应文件编码
【发布时间】:2016-06-20 16:28:57
【问题描述】:

我正在尝试使用TextEncoderTextDecoder 编写文件。我还需要将 65 与 ascii 表相加,并且在处理换行符时不要求和。我已经调整了here 提出的解决方案来使用文件 API 读取文件。但是我在处理编码时遇到了一些问题。

// write cames from fileEntry.createWriter

var result='0'+String.fromCharCode(124)+'1234'+String.fromCharCode(10); // 0|1234

var asciiArray=[];
var stringArray=[];
var fileContent='';
var tpmBuffer;
var uint8array=new TextEncoder().encode(result); // returns a Uint8Array containing the text given in parameters encoded
uint8array=uint8array.map((byte)=>byte+65); // shift :)

for(var i=0;i<uint8array.length;i++) {
    if(uint8array[i]!==75) {
       asciiArray.push(uint8array[i]);
    } else {
        // I cant shift line break!
        asciiArray.push(10);

        tpmBuffer= new TextEncoder().encode(String.fromCharCode.apply(null,asciiArray));
        stringArray.push(new TextDecoder("utf-8").decode(tpmBuffer));
      console.log(stringArray); //["q½rstu\n"]
        asciiArray=[];
    }
}

var encodedBlob= new Blob(stringArray, {
    encoding:'UTF-8',
    type: 'text/plain;charset=UTF-8'
});

// writer.write(encodedBlob);

当我尝试阅读生成的内容时,我得到以下信息:

    // Now we read the generated file content with:
    // fileContent = "q½rstu\n"
      var buf= new Uint8Array(fileContent);
      buf=buf.map((byte)=>byte-65);
      var fileAsString= new TextDecoder("ascii").decode(buf);

/*  
output bellow is given by console.log(fileAsString[i], fileAsString.charCodeAt(i));

0 48
 129 -> Why this guy appers?
| 124
1 49
2 50
3 51
4 52
*/

如果我在构建字符串时没有出现这个129 元素,为什么我在读取文件内容时会出现它?

【问题讨论】:

    标签: javascript encoding google-chrome-app fileapi


    【解决方案1】:

    129 元素来自buf.map((byte)=&gt;byte-65)
    如果我能理解这个符号,它会从buf 中的每个字节 中减去数字65

    它对于 // fileContent = "qrstu\n" 可以很好地工作,但如果 fileContent 包含非 ASCII 字符(超过 7 位),例如 // fileContent = "q½rstu\n",因为 ½ 将无法按预期工作 Vulgar Fraction One Half ,代码点U+00BD,被UTF-8编码为字节序列0xC20xBD

    基本cmd 算术set /a 0xc2 - 65 给出结果129

    顺便说一句,如果fileContent 中字符的ASCII 值小于65,我认为buf.map((byte)=&gt;byte-65) 可能会引发错误,假设byte 是无符号value 数据类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-05
      • 2011-12-24
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多