나는이 코드를 MDN File I/O 페이지에서 바로 복사했습니다. if 문을 추가하여 파일이 이미 존재하는지 확인하고 그럴 경우 대신 읽었습니다.로컬 컴퓨터의 파일 읽기/쓰기
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
var file = Components.classes["@mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("Desk", Components.interfaces.nsIFile);
file.append("test.txt");
if (!file.exists()) {
this.user_id = Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001);
var ostream = FileUtils.openSafeFileOutputStream(file)
var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(this.user_id);
// The last argument (the callback) is optional.
NetUtil.asyncCopy(istream, ostream, function(status) {
if (!Components.isSuccessCode(status)) {
alert('Error '+ status);
return;
}
alert('File created');
});
} else
{
NetUtil.asyncFetch(file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
alert('error '+ status);
return;
}
// The file data is contained within inputStream.
// You can read it into a string with
this.user_id = NetUtil.readInputStreamToString(inputStream, inputStream.available());
});
alert('File exists already, do not create');
}
alert(this.user_id);
파일을 잘 생성하여 열어서 읽을 수 있습니다. 그러나 파일이 이미있는 경우에는 this.user_id
.. 채우지 않습니다. 단지 null과 같습니다. 그래서 내 문제는 특히 파일을 읽는 것입니다. 코드가 완료된 것을 의미 NetUtil.asyncFetch()
에서 콜백 데이터로 호출되는 어떤 시점에서, 다음합니다 (alert()
this.user_id
이 null
것을 보여줍니다 호출 포함) - 코드 읽기
파일의 내용이 올바른지 확인 했습니까? –
@David - 당신이 무슨 뜻인지 안다면, 당신은'contentType'을 말하는 겁니까? – thefoyer