问题
In Haxe, is there any cross-language method for reading lines from a file (that works with all Haxe target languages?)
Here's the method stub that I'm trying to implement:
static function readLine(fileName, lineNumber){
//now how can I get this method to work with all Haxe target languages?
}
It might be possible to find a relevant method in the Sys class, but I haven't yet found it.
回答1:
static function readLine(fileName, lineNumber) {
var fin = sys.io.File.read(fileName, false);
try {
for (i in 0...lineNumber)
fin.readLine();
var line = fin.readLine();
fin.close();
} catch (e:haxe.io.Eof) { return null; }
return line;
}
http://haxe.org/api/sys/io/file is what you're looking for.
http://haxe.org/doc/neko/fileio for an example.
回答2:
Currently for haxe node target because of the async aspect the approach to reading line numbers is perhaps a bit different so thought it might be useful to add an example wrapper that makes it easier, just pass the class the file path, a function to process the lines and a function when finished processing.
package saver;
import js.node.Fs;
import js.node.Readline;
class Reader{
var onLine: Int->String->Void;
var finished: Void->Void;
var lineNo: Int;
public function new( file_: String
, onLine_: Int->String->Void
, finished_: Void->Void ){
onLine = onLine_;
finished = finished_;
var file = file_;
lineNo = 0;
var readLine = Readline.createInterface({
input: Fs.createReadStream( file )
});
readLine.on('line', onReadLine );
readLine.on('close', onFinished );
}
function onReadLine( str ){
onLine( lineNo, str );
lineNo++;
}
function onFinished( ){
finished();
}
}
If your using Node in an electron app then you probably need these in your hxml.
-lib electron
-lib hxnodejs
来源:https://stackoverflow.com/questions/13355099/reading-lines-from-a-file-in-haxe