【发布时间】:2018-03-24 18:11:40
【问题描述】:
我有一个疑问,因为我需要读取一个本地文件并且我一直在研究一些线程,并且我看到了各种处理它的方法,在大多数情况下都有一个输入文件。
我需要直接通过代码加载它。
我研究过这个帖子:
How to read a local text file?
而且我可以阅读它。
令人惊讶的是,当我尝试拆分行和单词时,它显示: � 替换重音字母。
我现在的代码是:
myFileReader.js
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText;
console.log('The complete text is', allText);
let lineArr = intoLines(allText);
let firstLineWords = intoWords(lineArr[0]);
let secondLineWords = intoWords(lineArr[1]);
console.log('Our first line is: ', lineArr[0]);
let atlas = {};
for (let i = 0; i < firstLineWords.length; i++) {
console.log(`Our ${i} word in the first line is : ${firstLineWords[i]}`);
console.log(`Our ${i} word in the SECOND line is : ${secondLineWords[i]}`);
atlas[firstLineWords[i]] = secondLineWords[i];
}
console.log('The atlas is: ', atlas);
let atlasJson = JSON.stringify(atlas);
console.log('Atlas as json is: ', atlasJson);
download(atlasJson, 'atlasJson.txt', 'text/plain');
}
}
};
rawFile.send(null);
}
function download(text, name, type) {
var a = document.getElementById("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
}
function intoLines(text) {
// splitting all text data into array "\n" is splitting data from each new line
//and saving each new line as each element*
var lineArr = text.split('\n');
//just to check if it works output lineArr[index] as below
return lineArr;
}
function intoWords(lines) {
var wordsArr = lines.split('" "');
return wordsArr;
}
疑问是:我们如何处理那些特殊字符,即带重音的元音?
我问这个,因为即使在 IDE 中,如果我们以 UTF-8 加载 txt,也会出现询问标记,所以我改为 ISO-8859-1 并且加载良好。
我也学过:
Read UTF-8 special chars from external file using Javascript
Convert special characters to HTML in Javascript
Reading a local text file from a local javascript file?
另外,您能否解释一下是否有更短的方法可以在客户端 javascript 中加载文件。例如在 Java 中有 FileReader / FileWriter / BufferedWriter。 Javascript中有类似的东西吗?
感谢您的帮助!
【问题讨论】:
-
“另外...” 在 SO 上,问 一个 问题/问题很重要,而不是两个(或更多)。 (我正要链接到说明这一点的帮助页面......我没有找到一个。这是帮助的问题。:-))
-
接受文本文件的第一步是知道它使用哪种字符编码。
标签: javascript html utf-8 character-encoding