2013-02-15 92 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);