#array of double to a file

1 messages · Page 1 of 1 (latest)

cloud raft
#

i have to write an array of double to a .dat file, and i have to get the bytes of the array and write it to the file. And when reading it i have read the array in one go and to use an offset to read any array beyond that, and i have no idea how to do it

split jungleBOT
#

<@&987246399047479336> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#
TJ-Bot
I have to write an array of double to a .dat file, and i have to get the bytes of the array and write it to the file. And when reading it i have to use an offset to read the array, and i have no idea how to do it

correct portion of the file. Here's an example of how you can write an array of double to a .dat file in Java:

import java.io.*;

public class WriteArrayToFile {
    public static void main(String[] args) {
        double[] arr = {1.2, 3.4, 5.6, 7.8};

        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"))) {
            for (double num : arr) {
                dos.writeDouble(num);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

To read the array from the file with an offset, you can do something like this:

import java.io.*;

public class ReadArrayFromFile {
    public static void main(String[] args) {
        int offset = 8; // Number of bytes to skip

        try (DataInputStream dis = new DataInputStream(new FileInputStream("data.dat"))) {
            // Skip bytes based on offset
            dis.skipBytes(offset);

            while (dis.available() > 0) {
                double num = dis.readDouble();
                System.out.println(num);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we use DataOutputStream to write the array of doubles to the file and DataInputStream to read it back with an offset. Remember to handle exceptions properly when working with I/O operations in Java.

cloud raft
#

also i was told to write the array of doubles as bytes, and read it from the file in one go

strong kettle
#

Create a ByteBuffer.allocate the size of your double array * Double.BYTES, get it as a DoubleBuffer with asDoubleBuffer. And write all the doubles in there with .put

#

(and optionally choose the endianness of that bytebuffer with .order)

cloud raft
#

how will i be able to read it from the file again?

strong kettle
#

read the file into a bytebuffer, create a doublebuffer from it, and get the array out

cloud raft
#

ah ok, ill try that and see how it goes

#

are there any example of this online? this is my first time hearing about them

strong kettle
#

probably a couple, but it's a relatively easy api

#

So just go for it?