
On 12/5/07 12:15 PM, "Prof Brian Ripley" <ripley@stats.ox.ac.uk> wrote:

On Wed, 5 Dec 2007, David Coppit wrote:

> Or, given that I'm dealing with just a single array, would it be better to
> roll my own I/O using write.table or write.matrix from the MASS package?

It would be much easier.  The save() format is far more complex than you
need.  However, I would use writeBin() to write a binary file and read
that in in Java, avoiding the binary -> ASCII -> binary conversion.

Thanks for the suggestion-writeBin works quite well. For posterity, here's what I did:

On the R side:

# Assumes that there are no special values in the tofList, such as NA_REAL,
# R_PosInf, R_NegInf, ISNAN, R_FINITE. See the "R Data Import/Export" manual.
saveListAsBinary <- function( tofList, filename )
{
  outConn <- file( filename, "wb" );

  for (m in 1:length(tofList)) {
    writeBin(names(tofList)[[m]], outConn);
    writeBin(length(tofList[[m]]), outConn, size = 4, endian = "big");
    writeBin(tofList[[m]], outConn, size = 4, endian = "big");
  }

  close(outConn);
}

saveListAsBinary(myList, "outfile.RDat");

On the Java side:

  public static void read_R_Output(String filename, ArrayList<String> names,
      ArrayList<ArrayList<Float>> data)
  {
    try {
      DataInputStream dataInputStream = new DataInputStream(
        new BufferedInputStream(new FileInputStream(filename)));

      boolean endOfFile = false;

      while (!endOfFile) {
        try {
          StringBuffer sb = new StringBuffer();

          byte c;
          while ((c = dataInputStream.readByte()) != 0)
            sb.append((char)c);

          names.add(new String(sb));

          int cols = dataInputStream.readInt();

          ArrayList<Float> row = new ArrayList<Float>(cols);

          for (int i = 0; i < cols; i++)
            row.add(dataInputStream.readFloat());

          data.add(row);
        } catch (EOFException e) {
          endOfFile = true;
        }
      }

      dataInputStream.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

Regards,
David

	[[alternative HTML version deleted]]

