I have a 500MB binary file. with a bunch of float entries. It was written by a C++ program. I would load it in C++ like this.
void load(char f_name[], int size, float data[])
{
std::fstream f_bin(f_name, std::ios::in|std::ios::binary);
f_bin.seekg(std::ios::beg);
f_bin.read((char*)data, size*sizeof(float));
f_bin.close();
}
float *data;
int size = 123456789;
data = new float[size];
load("myFile.bin", size, data);
And i can access the float values: data[x]; In c++ it works preatty fast. Is there something simular in java?
Edit After reading a bit around i have this so far:
RandomAccessFile f = new RandomAccessFile("C://path//myFile.bin", "r");
byte[] bytes = new byte[(int)f.length()];
f.read(bytes);
float fl = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();
System.out.println(fl);
Which prints the first float entry. Now i should loop float by float and put it in an array like float[] data
.
You can do this in Java.
try(FileChannel fc = new RandomAccessFile("myFile.bin", "rw").getChannel()) {
FloatBuffer fb = fc.map(MapMode.READ_WRITE, 0, fc.size())
.order(ByteOrder.nativeOrder()).asFloatBuffer();
// use fb
}
This is quite a bit faster as it memory maps the file and avoids a memory copy (you can do the same in C++)