How to read in writeBin() output from R into Java?

Clarinetist :

Consider the following R code:

f <- file("test.txt", "wb")
writeBin(c(1.2, 2.3, 3.4), f)
close(f)

I have written the following code in Java to try to read these data:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.PrintWriter;

public class readBinary {

    public static void main(String[] argv) throws IOException {
        DataInputStream fileIn = new DataInputStream(new FileInputStream(argv[0]));
        FileOutputStream fileOut = new FileOutputStream(argv[1]);
        PrintWriter fileOutWriter = new PrintWriter(fileOut);

        int rows = Integer.parseInt(argv[2]);
        int cols = Integer.parseInt(argv[3]);

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                fileOutWriter.print(fileIn.readDouble() + " ");
            }
            fileOutWriter.println();
        }
        fileOutWriter.close();
    }

}

In the command line:

javac readBinary.java
java readBinary test.txt test_new.txt 3 1

The test_new.txt file outputs:

4.667261458438315E-62 
1.9035985662475526E185 
4.667261458387024E-62 

So Java is not picking this up as three doubles correctly.

Thus, I ask, what exactly is the output of writeBin, and how could it be read into Java so that the intended numbers are read in correctly?

Andrey Shabalin :

Java in big-endian by default. Thus please try using writeBin(..., endian = "big")

f <- file("test.txt", "wb")
writeBin(c(1.2, 2.3, 3.4), f, endian = "big")
close(f)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=396754&siteId=1