Skip to content

Instantly share code, notes, and snippets.

@grssam
Created July 26, 2012 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grssam/3181215 to your computer and use it in GitHub Desktop.
Save grssam/3181215 to your computer and use it in GitHub Desktop.
Read a local file line by line
let {Ci: interfaces, Cc: classes, Cu: utils} = Components;
let ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
let file = ios.newURI(<file address>, null, null).QueryInterface(Ci.nsIFileURL).file;;
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = /* The character encoding you want, using UTF-8 here */ "UTF-8";
let fis = Cc["@mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream);
fis.init(file, -1, -1, 0);
let lis = fis.QueryInterface(Ci.nsILineInputStream);
let lineData = {};
let cont;
do {
cont = lis.readLine(lineData);
let lineString = converter.ConvertToUnicode(lineData.value);
// This lineString cariable contains the string for the line.
} while (cont);
// Close the stream afterwards.
fis.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment