2013-02-15 96 views
0

我有这段JavaScript代码无法读取该文件的全部内容在JavaScript

var file = Components.classes["@mozilla.org/file/local;1"] 
      .createInstance(Components.interfaces.nsILocalFile); 
file.initWithPath(this.savefile); 
if (file.exists() == false) { 
    return null; 
} 
var is = Components.classes["@mozilla.org/network/file-input-stream;1"] 
      .createInstance(Components.interfaces.nsIFileInputStream); 
is.init(file,0x01, 00004, null); 
var sis = Components.classes["@mozilla.org/scriptableinputstream;1"] 
      .createInstance(Components.interfaces.nsIScriptableInputStream); 
sis.init(is); 
output = sis.read(sis.available()); 

sis.close(); 
is.close(); 
this.filterData = output; 
return output; 

的:其实这个我读的文件是一个二进制文件,并让说,350个字节。 现在19字节是“零”,所以会发生什么是在上面的代码中我只得到了18个字节输出

,当我试图调试sis.available不会返回350.但是sis.read只读取高达零字节。

我想要的方式来读取输出中的整个350字节。

+0

只是要清楚,SAVEFILE是本地的?这是一个Firefox附加组件,对吧? – 2013-02-15 09:26:57

+0

@JonathanFingland对。 – 2013-02-15 09:28:46

+1

这可能是也可能不是相关的,但请参阅https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIScriptableInputStream,其中read()带有警告:如果数据包含空字节,则此方法将返回一个截断的字符串。您可能需要使用readBytes()。 – 2013-02-15 09:34:32

回答

1

编辑

https://developer.mozilla.org/en-US/docs/Reading_textual_data

报价:

var charset = /* Need to find out what the character encoding is. Using UTF-8 for this example: */ "UTF-8"; 
var is = Components.classes["@mozilla.org/intl/converter-input-stream;1"] 
       .createInstance(Components.interfaces.nsIConverterInputStream); 
// This assumes that fis is the nsIInputStream you want to read from 
is.init(fis, charset, 1024, 0xFFFD); 
is.QueryInterface(Components.interfaces.nsIUnicharLineInputStream); 

if (is instanceof Components.interfaces.nsIUnicharLineInputStream) { 
    var line = {}; 
    var cont; 
    do { 
     cont = is.readLine(line); 

     // Now you can do something with line.value 
    } while (cont); 
} 

这就避免了空字节的问题,是unicode的安全,与较不深奥的对象类型一起工作。

原文:

按照我上面的评论,在你编辑的光,

https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIScriptableInputStream,其中的read()自带的警告:如果数据包含一个空字节,那么这方法将返回一个截断的字符串。您可能需要使用readBytes()。

另外,这里是另一种方式来做到这一点:

var ph = Components.classes["@mozilla.org/network/protocol;1?name=file"] 
      .createInstance(Components.interfaces.nsIFileProtocolHandler); 

var file_to_read = ph.getURLSpecFromFile(file); 

var req = new XMLHttpRequest(); 
req.onerror = function(e) { 
     onError(e); 
} 


req.onreadystatechange = function() { 
     if (log.readyState == 4) { 
     //... 
     } 
} 

req.open("GET", file_to_read, true);