Newsgroups: comp.lang.apl
Path: watmath!watserv1!utgpu!news-server.csri.toronto.edu!rpi!think.com!ames!haven.umd.edu!socrates!socrates!rockwell
From: rockwell@socrates.umd.edu (Raul Deluth Miller-Rockwell)
Subject: Re: File I/O in J.
In-Reply-To: bli@lynx.cat.syr.edu's message of Tue, 28 Jan 92 02:40:28 ES
Message-ID: <ROCKWELL.92Jan28091229@socrates.umd.edu>
Sender: rockwell@socrates.umd.edu (Raul Deluth Miller-Rockwell)
Organization: Traveller
References: <1992Jan28.024028.18052@newstand.syr.edu>
Date: Tue, 28 Jan 1992 14:12:29 GMT

Bin Li:
   Hi, Could someone show me how to read/write an array from/to an
   external file (binary or decimal)?  Thanks.

There's more than one way to do this.  For example, the simplest to
use from inside J is probably:
   'global_array_name' 2!:2&< 'file_name'

This creates or updates a "workspace", which is a collection of J
objects (of any type) which can be brought back into your session with
an expression like:
   'global_array_name' 2!:1&< 'file_name'

Note that multiple arrays and/or multiple files can be written with
this command.  For example,
   ('a1';'a2';'a3') 2!:2 <'file_name'

There is documentation in the file 'status.doc' [which comes with the
J binaries] on the format which is used to save these workspace files.

----------------------------------------------------------------------

Another way to write files is:
   array 1!:2 <'file_name'

However, this only works with character arrays.  You can read them
back in using:
   1!:1 <'filename'

which returns the character array as a specific result.  If it's
important to use this sort of technique with something other than a
character array, there are a couple techniques for converting flat
arrays (not boxed arrays) to an internal representation (that is, a
character array) and back again.  For example,
   (3!:1 array) 1!:2 <'file_name'
to store a binary array to file, and
   (3!:2) 1!:1 <'file_name'
to read the binary array back in, and return it as an explicit result.

Note that the binary format of arrays is subject to change in future
versions of J.

----------------------------------------------------------------------

Finally, you could put the array out as formatted data, which can be
handy when you need to use the information in some program other than
J.  There are a large number of ways of doing this, depending on how
the 'other program[s]' use files.  But, the simplest I can think of
is:
   (, ,"1&(10{a.) ": array) 1!:2 <'file_name'
to write a 2 dimensional array to disk, and
   (".;._2) 1!:1 <'file_name'
to read it back in.

[Note that this particular example assumes no blank lines or comments
in the file being read in, and that the last line end with a newline
character.  Also, it doesn't strip off unwanted control characters
should they occur, though that isn't hard to add.]

-- 
Raul Deluth Miller-Rockwell                  <rockwell@socrates.umd.edu>
The U.S. Federal government went another billion dollars into debt today.
