Reading lines from a file in Haxe

て烟熏妆下的殇ゞ 提交于 2019-12-11 11:57:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!