Facility Control

 View Only
Expand all | Collapse all

How to detect end of file when reading in a plain text file

  • 1.  How to detect end of file when reading in a plain text file

    Posted 09-29-2017 10:47

    Hi,

    I am trying to read in a plain text file line by line inside dashboard with ogscript.

    How do I detect the end of the file?

    When I use readLine() in a while loop I get "Wrapped java.io.EOFException (Element API#7)" when I am past the last line in the file.

    Below is the code I use:

    function readTextFile(path){
    var textFile = ogscript.createFileInput(path);
    var line = "";

    while((line = textFile.readLine()) != -1){
    ogscript.debug(line);
    }

    textFile.close();
    ogscript.debug("File closed");
    }


  • 2.  RE: How to detect end of file when reading in a plain text file

    Posted 09-29-2017 15:21

    Hi Svein.
    At present, you would need to have your file end with a newline to read the final line.
    I will add a feature request to have it automatically return the last line of the file if it hits an EOF and to return null if called after hitting EOF.

    For your existing application, if the file does end with a newline, I would recommend:

    function readTextFile(path){
    var textFile = ogscript.createFileInput(path);
    var line = "";
    
    try
    {
       while((line = textFile.readLine()) != null)
       {
            ogscript.debug(line);
       }
    }
    catch (e)
    {
       //END OF FILE
    }
    
    textFile.close();
    ogscript.debug("File closed");
    }

    Another option would be to read the entire file and split it into an array of Strings based on the newline character:

    function readTextFile(path)
    {
       var textFile = ogscript.createFileInput(path);
       var allText = textFile.readString(textFile.getSize());
       textFile.close();
       
       var allLines = allText.split("\n");
       for (var i = 0; i < allLines.length; i++)
       {
          ogscript.debug(allLines[i]);
       }
    }



    #DashBoard