繁体   English   中英

使用Chrome File System API写入文件时,文件编码不适合

[英]Can't fit file encoding when writing a file with Chrome File System API

我正在尝试使用TextEncoderTextDecoder写入文件。 我还需要将65加到ascii表中,而不要在处理换行符时求和。 我已经调整了此处提出的解决方案以使用文件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元素,为什么在读取fileContent时出现此129元素?

129元素来自buf.map((byte)=>byte-65)
如果我能理解这种表示法,它将从buf每个字节中减去数字65

// fileContent = "qrstu\\n"可能效果很好,但如果fileContent包含非ASCII字符(超过7位),则无法正常工作,例如// fileContent = "q½rstu\\n"因为½ 分数二分之一 ,码点U+00BD ,是UTF-8编码为字节序列0xC20xBD

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM