I wrote a Java program to output numeric data to binary .txt file and plan to use Matlab to process that data file.
In the Java program, I used DataOutputStream to write float numbers to data.txt file and test by using DataInputStream to read data.txt what wrote earlier. And I got right result.
// write {1.0, 2.0, 3.0, 4.0, 5.0, 6.0}
private void writeFile(Float [] data) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream dos = new DataOutputStream(fis);
for (int i = 0; i < data.length; ++i) {
dos.writeFloat(data[i]);
}
dos.close();
}
//output is {1.0, 2.0, 3.0, 4.0, 5.0, 6.0}
private float[] readFile( String fileName, int size) throws IOException {
FileInputStream fis = new FileInputStream(fileName);
DataInputStream dis = new DataInputStream(fis);
float [] dataArray = new int[size];
for (int i = 0; i < dataArray.length; ++i) {
dataArray[i] = dis.reaFloat();
}
dis.close();
return dataArray;
}
However, when I use data.txt file in matlab, I got wrong number.
fid = fopen('data.txt');
data = fread(fid, 'float');
fclose all;
What I got back is:
data =
1.0e-40 *
0.4601
0.0009
0.2305
0.4601
0.5749
0.6897
So, I doubt that that might be a problem with my convert from binary to float in Matlab. Any recommendation is appreciated.
Or is there any other way to write primitive data from Java and process in Matlab? Thanks.