如何将 R 的 writeBin() 输出读入 Java?
How to read in writeBin() output from R into Java?
考虑以下 R 代码:
f <- file("test.txt", "wb")
writeBin(c(1.2, 2.3, 3.4), f)
close(f)
我在Java中编写了以下代码来尝试读取这些数据:
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();
}
}
在命令行中:
javac readBinary.java
java readBinary test.txt test_new.txt 3 1
test_new.txt 文件输出:
4.667261458438315E-62
1.9035985662475526E185
4.667261458387024E-62
所以 Java 没有正确地将其视为三双。
因此,请问,writeBin 的输出到底是什么,如何将其读入 Java 以便正确读入预期的数字?
Java 默认为大端。因此请尝试使用 writeBin(..., endian = "big")
f <- file("test.txt", "wb")
writeBin(c(1.2, 2.3, 3.4), f, endian = "big")
close(f)