How can we read a text file through javascript (helper scrip

Posted by nithinonpsdn on 08-Jun-2010 10:54

I need to open and read a text file and based on the value contained there I need to implement CBR.

Please help me in reading the text file using javascript which we can use as helper scripts in CBR.

All Replies

Posted by tsteinbo on 08-Jun-2010 14:17

You can use normal java classes from javascript. We use the Rhino engine. Please refer to their documentation for all possibilities.

In short though it will be something like

var fileStream = new package.java.io.FileInputStream("path");

fileStream.open();

filestream.read();

etc etc

HTH

Thomas

PS.: Writing this from the top of my head, so excuse if the syntax is not perfect.

Posted by nithinonpsdn on 09-Jun-2010 04:11

Can't we use BufferedReader in the Javascript section in CBR (Sonic)? I need to read every line and load it into an arraylist.

So the BufferedReader would be very helpful in this regard.

But I am not able to do as it keeps throwing exceptions.

Kindly help me in this regard.

Posted by tsteinbo on 09-Jun-2010 04:19

All Java classes should work. Please paste your code snippet and the error you getting.

Posted by nithinonpsdn on 09-Jun-2010 04:41

Hi Thomas

    Thanks for your time and inpus. I tried now and got it

Cheers

Nithin.

Posted by nithinonpsdn on 09-Jun-2010 04:42

function loadItems()

{

br = new java.io.BufferedReader(new java.io.FileReader(new java.io.File("path")));

line = br.readLine();

ItemsInfo = new java.util.ArrayList();

while(line!=null)

{

ItemsInfo.add(line.trim());

line = br.readLine();

}

br.close();

}

Posted by tsteinbo on 09-Jun-2010 05:35

The syntax needs to include the "Packages." prefix for anything not in java.lang. Eg. write:

br = new Packages.java.io.BufferedReader(new Packages.java.io.FileReader(new  Packages.java.io.File("path")));

That should hopefully do. If not: what is the exception?

Thomas

Posted by nithinonpsdn on 09-Jun-2010 06:20

But I tried even without the 'Packages' prefix and it worked without any exceptions.

How can we externalise the path?? It is not accepting the SonicFS path. I had to hardcode the local-drive path to make it work.

I was not able to use relative path too. Any way around this?

Posted by tsteinbo on 09-Jun-2010 06:32

You can access sonicfs (it is a URL not a file!) using the URL/URLConnection classes, e.g. new URL("sonicfs:///path/to/my/file"); Then open it and read the content as you would from a file.

Relative paths (to files) will work as well. Paths will be relative to the container's working directory and not the Sonic installation directory.

Externalizing paths: Just pass in a parameter to your method and populate it from say a message header etc etc.

Thomas

PS.: Seems the prefix is needed only for none-standard java packages.

Posted by nithinonpsdn on 09-Jun-2010 08:32

Thanks Thomas.

This thread is closed